Using named routes in laravel

There may be times when we need to change our route’s name. On a large site, this could
cause a lot of problems if we have multiple links to an incorrect route. Laravel provides an
easy-to-use way of assigning names to our routes, so we never have to worry if they change.

how to do..

To complete this recipe, follow these steps:
1. In our routes.php file, create a named route as follows:
Route::get(‘main-route’, array(‘as’ => ‘named’, function()
{
return ‘Welcome to ‘ . URL::current();
}));
2. Create a route that performs a simple redirect to the named route:
Route::get(‘redirect’, function()
{
return Redirect::route(‘named’);
});
3. Create a route that displays a link to the named route:
Route::get(‘link’, function()
{
return ‘<a href=”‘ . URL::route(‘named’) . ‘”>Link!</a>’;
});
4. In the browser, visit http://your-server/redirect and
http://your-server/link (where your-server is the URL for
the server) and notice that they send us to the main-route route.
5. Now, rename the main-route route to new-route:
Route::get(‘new-route’, array(‘as’ => ‘named’, function()
{
return ‘Welcome to ‘ . URL::current();
}));
6. In the browser, visit the redirect and link routes and see where they send us now.

how its works…

There may be times when your route will need to change; for example, if a client has a
blog but wants the route “posts” to become “articles”. If we have links to the “posts” route
throughout our site, it would mean we need to find every file and make sure they’re changed.
By using a named route, we can rename the route to anything we want, and as long as all our
links point to the name, everything will stay updated.

Leave a Reply

Your email address will not be published. Required fields are marked *