- Basic Routing
- Route Parameters
- Route Filters
- Named Routes
- Route Groups
- Sub-Domain Routing
- Route Prefixing
- Route Model Binding
- Throwing 404 Errors
- Routing To Controllers
Most of the routes for your application will be defined in the app/Http/routes.php
file. This file is loaded by the App\Providers\RouteServiceProvider
class, and you are free to change the location of your routes file. The simplest Laravel routes consist of a URI and a Closure callback.
Route::get('/', function()
{
return 'Hello World';
});
Route::post('foo/bar', function()
{
return 'Hello World';
});
Route::match(array('GET', 'POST'), '/', function()
{
return 'Hello World';
});
Route::any('foo', function()
{
return 'Hello World';
});
Route::get('foo', array('https', function()
{
return 'Must be over HTTPS';
}));
Often, you will need to generate URLs to your routes, you may do so using the URL::to
method:
$url = URL::to('foo');
Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
Route::get('user/{name?}', function($name = null)
{
return $name;
});
Route::get('user/{name?}', function($name = 'John')
{
return $name;
});
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');
Route::get('user/{id}', function($id)
{
//
})
->where('id', '[0-9]+');
Of course, you may pass an array of constraints when necessary:
Route::get('user/{id}/{name}', function($id, $name)
{
//
})
->where(array('id' => '[0-9]+', 'name' => '[a-z]+'))
If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern
method. It is recommended that you define these patterns in the before
method of your RouteServiceProvider
:
public function before()
{
Route::pattern('id', '[0-9]+');
}
Once the pattern has been defined, it will be applied to all routes using that parameter:
Route::get('user/{id}', function($id)
{
// Only called if {id} is numeric.
});
If you need to access a route parameter value outside of a route, you may use the input
method. For instance, within a filter class, you might do something like the following:
public function filter($route, $request)
{
if ($route->input('id') == 1)
{
//
}
}
Route filters provide a convenient way of limiting access to a given route, which is useful for creating areas of your site which require authentication. There are several filters included in the Laravel framework, including an auth
filter, an auth.basic
filter, a guest
filter, and a csrf
filter. These are located in the app/Http/Filters
directory.
To create a new route filter, you may use the filter:make
Artisan command:
php artisan filter:make OldFilter
This command will place a new OldFilter
class within your app/Http/Filters
directory. You can insert your filter logic within the class:
public function filter($route, $request)
{
if ($request->input('age') < 200)
{
return Redirect::to('home');
}
});
If the filter returns a response, that response is considered the response to the request and the route will not execute. Any after
filters on the route are also cancelled.
To register the filter with your application, you should add it to the array of route filters in the app/Providers/FilterServiceProvider.php
class:
/**
* All available route filters.
*
* @var array
*/
protected $filters = [
'auth' => 'App\Http\Filters\AuthFilter',
'auth.basic' => 'App\Http\Filters\BasicAuthFilter',
'csrf' => 'App\Http\Filters\CsrfFilter',
'guest' => 'App\Http\Filters\GuestFilter',
'old' => 'App\Http\Filters\OldFilter',
];
Route::get('user', array('before' => 'old', function()
{
return 'You are over 200 years old!';
}));
Route::get('user', array('before' => 'old', 'uses' => 'UserController@showProfile'));
Route::get('user', array('before' => 'auth|old', function()
{
return 'You are authenticated and over 200 years old!';
}));
Route::get('user', array('before' => array('auth', 'old'), function()
{
return 'You are authenticated and over 200 years old!';
}));
public function filter($route, $request, $value)
{
//
}
Route::get('user', array('before' => 'age:200', function()
{
return 'Hello World';
}));
After filters receive a $response
as the third argument passed to the filter:
public function filter($route, $request, $respones)
{
//
}
You may also specify that a filter applies to an entire set of routes based on their URI. You should register these pattern based filters within your app/Providers/RouteServiceProvider.php
file's before
method:
public function before()
{
$this->when('admin/*', 'admin');
}
In the example above, the admin
filter would be applied to all routes beginning with admin/
. The asterisk is used as a wildcard, and will match any combination of characters.
Note: From within the
RouteServiceProvider
you may call any method that is on theIlluminate\Routing\Router
class.
You may also constrain pattern filters by HTTP verbs:
public function before()
{
$this->when('admin/*', 'admin', ['post']);
}
Named routes make referring to routes when generating redirects or URLs more convenient. You may specify a name for a route like so:
Route::get('user/profile', array('as' => 'profile', function()
{
//
}));
You may also specify route names for controller actions:
Route::get('user/profile', array('as' => 'profile', 'uses' => 'UserController@showProfile'));
Now, you may use the route's name when generating URLs or redirects:
$url = URL::route('profile');
$redirect = Redirect::route('profile');
You may access the name of a route that is running via the currentRouteName
method:
$name = Route::currentRouteName();
Sometimes you may need to apply filters to a group of routes. Instead of specifying the filter on each route, you may use a route group:
Route::group(array('before' => 'auth'), function()
{
Route::get('/', function()
{
// Has Auth Filter
});
Route::get('user/profile', function()
{
// Has Auth Filter
});
});
You may also use the namespace
parameter within your group
array to specify all controllers within that group as being in a given namespace:
Route::group(array('namespace' => 'Admin'), function()
{
//
});
Note: By default, the
RouteServiceProvider
includes yourroutes.php
file within a namespace group, allowing you to register controller routes without specifying the full namespace.
Laravel routes are also able to handle wildcard sub-domains, and pass you wildcard parameters from the domain:
Route::group(array('domain' => '{account}.myapp.com'), function()
{
Route::get('user/{id}', function($account, $id)
{
//
});
});
A group of routes may be prefixed by using the prefix
option in the attributes array of a group:
Route::group(array('prefix' => 'admin'), function()
{
Route::get('user', function()
{
//
});
});
Model binding provides a convenient way to inject model instances into your routes. For example, instead of injecting a user's ID, you can inject the entire User model instance that matches the given ID. First, use the router's model
method to specify the model that should be used for a given parameter. For example, in your RouteServiceProvider::before
method:
public function before()
{
$this->model('user', 'User');
}
Next, define a route that contains a {user}
parameter:
Route::get('profile/{user}', function(User $user)
{
//
});
Since we have bound the {user}
parameter to the User
model, a User
instance will be injected into the route. So, for example, a request to profile/1
will inject the User
instance which has an ID of 1.
Note: If a matching model instance is not found in the database, a 404 error will be thrown.
If you wish to specify your own "not found" behavior, you may pass a Closure as the third argument to the model
method:
public function before()
{
$this->model('user', 'User', function()
{
throw new NotFoundHttpException;
});
}
Sometimes you may wish to use your own resolver for route parameters. Simply use the Route::bind
method:
public function before()
{
$this->bind('user', function($value, $route)
{
return User::where('name', $value)->first();
});
}
There are two ways to manually trigger a 404 error from a route. First, you may use the App::abort
method:
App::abort(404);
Second, you may throw an instance of Symfony\Component\HttpKernel\Exception\NotFoundHttpException
.
More information on handling 404 exceptions and using custom responses for these errors may be found in the errors section of the documentation.
Laravel allows you to not only route to Closures, but also to controller classes, and even allows the creation of resource controllers.
See the documentation on Controllers for more details.