Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bsapaka's avatar

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']);
0 likes
6 replies
bestmomo's avatar

What dont you understand ? The route "foo" uses the controller "FooController", method "method" and can be called as "name".

1 like
nztim's avatar

Previously in the documentation it is stated that closure routes can be named. That part is just saying that controller routes can also be named, and provides the syntax.

The explanation for named routes is here: http://laravel.com/docs/5.1/routing#named-routes, however the gist is that by giving a route a name, you can refer to the route by name rather than by the URI.

bsapaka's avatar

nztim, not sure if I am making an error or missing it totally, but here's what I have:

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

Route::get('qux', function() {
    action('bar');
});

But calling /bar or /qux in the URL gives me a NotFoundHttpException

1 like
nztim's avatar

The name of a route is not an alias that can be used in the browser. In your first example, the route will only be triggered by a get request to domain.com/foo.

The purpose of the route name is to provide a way to refer to the route in your code. So instead of using url('foo'); you can use route('bar');. One of the advantages to this is that if you want to change the URI from foo to account, you need only update the route definition, not all the references to it.

Your second example has correct syntax, but 'bar' is not a controller action, 'bar' is the name of a route. You could try this to demonstrate:

Route::get('qux', function() {
    var_dump(url('foo'));
    var_dump(route('bar'));
});
2 likes
nztim's avatar

A practical example of route naming:

Route::get('admin/pages/{id}/edit', ['as' => 'page.edit', 'uses' => 'PageController@edit']);

Which is nicer: url("admin/pages/{$id}/edit") or route('page.edit', $id)?

2 likes

Please or to participate in this conversation.