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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With