Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - please explain Naming Controller Routes 'uses', 'as'

I'm sure this is very simple, but I do not understand. Please explain this, from the documentation:

Naming Controller Routes Like Closure routes, you may specify names on controller routes:

Route::get('foo', ['uses' => 'FooController@method', 'as' => 'name']);

I am unclear as to the purpose of 'uses', 'as', and 'name', and how to use them.


Update:

So I have named a route closure as 'bar' but I get a NotFoundHttpException when trying to call /bar or /qux in the URL

Route::get('foo', ['as' => 'bar', function() {
    dd('foo');
}]);

Route::get('qux', function() {
    action('bar');
});
like image 568
brietsparks Avatar asked Dec 06 '15 21:12

brietsparks


1 Answers

uses specifies which class you're calling when the route hits, and which method on that class. So for Laravel 5.1, with your example, that would by default be the method method() on the class app/Http/Controllers/FooController.php

as means you give the route a name, so that it's easier to link to it later. Let's say you have ten views and you link to the same route from all of them. If you change the format of the link, you'll have to track each one individually and change them as well. But if you have given your route a name, you don't have to change anything, because they'll just look the route up by that name.

Putting it together, let's say you have a webshop and you want a route for your customers page, and that you want to link to it from your views. It might look something like this:

Route::get('customers', [
    'uses' => 'ShopController@customers',
    'as' => 'customers'
]);
like image 122
Joel Hinz Avatar answered Sep 29 '22 17:09

Joel Hinz