Laravel using named routes

Regarding the use of named routes, these two lines allow me to access the same page so that it 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 why I should use named routes if the latter is shorter and less error prone?

+4
source share
3 answers

The only advantage is that it’s easier to link, and you can change the URL without going through and changing all of its links. For example, using the named routes, you can do such things:

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'));

URL- . URL-, - :

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
+2

, ?

named route, , url, name , :

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

, :

return Redirect::route('routename');

url , , url, . , route:

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

, name, url, :

return Redirect::to('apples');

, , , , :

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

url apples somethingelse, Redirect .

+3

The only reason you can name a route is to link it later. IE: from your page in the form or something else, check if you are on this route.

0
source

Source: https://habr.com/ru/post/1537001/


All Articles