What are Named Routes in Laravel?



In Laravel routes are defined inside the routes/ folder. All the routes that are required inside your project are defined inside routes/web.php.

Example 1

A simple example of defining route is as follows ?

Route::get('/', function () { return view('welcome'); });

So now when you hit the page http://localhost:8000/ you will be redirected to the view(?welcome').

Named routes are routes with names. A name is given to the route defined and the name later can be used in case the user wants to perform redirection.

Example 2

Here is an example of a named route

With function

Route::get('test/student', function() { // })->name('student_test');

With Controller

Route::get('test/student', [StudentController::class, 'test'] )->name('student_test');

Output

In the above example, the route test/student is given a name called student_test. When you check the output it will be as follows

Example 3

when you list the routes, the name column will have a name for named routes.

Command: PHP artisan route: list

The name is displayed for the test/student.

Example 4

Getting Url for Named Routes.

In this example will see how to get the URL by using the route name.

Route::get('test/student', function() { $url=route('student_test'); return $url; })->name('student_test');

Output

When you hit the URL: http://127.0.0.1:8000/test/student it will give you the output as shown below

http://127.0.0.1:8000/test/student

Example 5

Parameters inside named routes.

In this example will see how to access parameters passed to the named route.

Route::get('test/{studentid}/student', function($studentid) { $url=route('student_test',['studentid'=>1]); return $url; })->name('student_test');

Output

The output when you hit the URL: http://127.0.0.1:8000/test/1/student is as follows

http://127.0.0.1:8000/test/1/student
Updated on: 2022-08-30T13:56:04+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements