Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel using named routes

Tags:

php

laravel

Regarding the use of named routes, these 2 lines allow me to access the same page so which is correct?

// Named route
Route::get('test/apples', array('as'=>'apples', 'uses'=>'TestController@getApples'));

// Much simpler
Route::get('apples', 'TestController@getApples');

Is there any reason I should be using named routes if the latter is shorter and less prone to errors?

like image 930
enchance Avatar asked Apr 17 '14 18:04

enchance


2 Answers

Named routes are better, Why ?

It's always better to use a named route because insstsead of using the url you may use the name to refer the route, for example:

return Redirect::to('an/url');

Now above code will work but if you would use this:

return Redirect::route('routename');

Then it'll generate the url on the fly so, if you even change the url your code won't be broken. For example, check your route:

Route::get('apples', 'TestController@getApples');
Route::get('apples', array('as' => 'apples.show', 'uses' => 'TestController@getApples'));

Both routes are same but one without name so to use the route without name you have to depend on the url, for example:

return Redirect::to('apples');

But same thing you may do using the route name if your route contains a name, for example:

return Redirect::route('apples.show');

In this case, you may change the url from apples to somethingelse but still your Redirect will work without changing the code.

like image 147
The Alpha Avatar answered Nov 28 '22 09:11

The Alpha


The only advantage is it is easier to link to, and you can change the URL without going through and changing all of its references. For example, with named routes you can do stuff like this:

URL::route('apples');
Redirect::route('apples');
Form::open(array('route' => 'apples'));

Then, if you update your route, all of your URLs will be updated:

// from
Route::get('test/apples', array('as'=>'apples', 'uses'=>'TestController@getApples'));

// to
Route::get('new/apples', array('as'=>'apples', 'uses'=>'TestController@getApples'));

Another benefit is logically creating a URL with a lot parameters. This allows you to be a lot more dynamic with your URL generation, so something like:

Route::get('search/{category}/{query}', array(
    'as' => 'search',
    'uses' => 'SearchController@find',
));

$parameters = array(
    'category' => 'articles',
    'query' => 'apples',
);

echo URL::route('search', $parameters);
// http://domain.com/search/articles/apples
like image 28
Sam Avatar answered Nov 28 '22 09:11

Sam