Routing

Basic Routing

Most of the routes for your application will be defined in the app/routes.php file. The simplest Laravel routes consist of a URI and a Closure callback.

Basic GET Route

  1. Route::get('/', function()
  2. {
  3. return 'Hello World';
  4. });

Basic POST Route

  1. Route::post('foo/bar', function()
  2. {
  3. return 'Hello World';
  4. });

Registering A Route For Multiple Verbs

  1. Route::match(array('GET', 'POST'), '/', function()
  2. {
  3. return 'Hello World';
  4. });

Registering A Route Responding To Any HTTP Verb

  1. Route::any('foo', function()
  2. {
  3. return 'Hello World';
  4. });

Forcing A Route To Be Served Over HTTPS

  1. Route::get('foo', array('https', function()
  2. {
  3. return 'Must be over HTTPS';
  4. }));

Often, you will need to generate URLs to your routes, you may do so using the URL::to method:

  1. $url = URL::to('foo');

Route Parameters

  1. Route::get('user/{id}', function($id)
  2. {
  3. return 'User '.$id;
  4. });

Optional Route Parameters

  1. Route::get('user/{name?}', function($name = null)
  2. {
  3. return $name;
  4. });

Optional Route Parameters With Defaults

  1. Route::get('user/{name?}', function($name = 'John')
  2. {
  3. return $name;
  4. });

Regular Expression Route Constraints

  1. Route::get('user/{name}', function($name)
  2. {
  3. //
  4. })
  5. ->where('name', '[A-Za-z]+');
  6. Route::get('user/{id}', function($id)
  7. {
  8. //
  9. })
  10. ->where('id', '[0-9]+');

Passing An Array Of Wheres

Of course, you may pass an array of constraints when necessary:

  1. Route::get('user/{id}/{name}', function($id, $name)
  2. {
  3. //
  4. })
  5. ->where(array('id' => '[0-9]+', 'name' => '[a-z]+'))

Defining Global Patterns

If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method:

  1. Route::pattern('id', '[0-9]+');
  2. Route::get('user/{id}', function($id)
  3. {
  4. // Only called if {id} is numeric.
  5. });

Accessing A Route Parameter Value

If you need to access a route parameter value outside of a route, you may use the Route::input method:

  1. Route::filter('foo', function()
  2. {
  3. if (Route::input('id') == 1)
  4. {
  5. //
  6. }
  7. });

Route Filters

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/filters.php file.

Note: Filters are disabled when the application environment is testing.

Defining A Route Filter

  1. Route::filter('old', function()
  2. {
  3. if (Input::get('age') < 200)
  4. {
  5. return Redirect::to('home');
  6. }
  7. });

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.

Attaching A Filter To A Route

  1. Route::get('user', array('before' => 'old', function()
  2. {
  3. return 'You are over 200 years old!';
  4. }));

Attaching A Filter To A Controller Action

  1. Route::get('user', array('before' => 'old', 'uses' => '[email protected]'));

Attaching Multiple Filters To A Route

  1. Route::get('user', array('before' => 'auth|old', function()
  2. {
  3. return 'You are authenticated and over 200 years old!';
  4. }));

Attaching Multiple Filters Via Array

  1. Route::get('user', array('before' => array('auth', 'old'), function()
  2. {
  3. return 'You are authenticated and over 200 years old!';
  4. }));

Specifying Filter Parameters

  1. Route::filter('age', function($route, $request, $value)
  2. {
  3. //
  4. });
  5. Route::get('user', array('before' => 'age:200', function()
  6. {
  7. return 'Hello World';
  8. }));

After filters receive a $response as the third argument passed to the filter:

  1. Route::filter('log', function($route, $request, $response)
  2. {
  3. //
  4. });

Pattern Based Filters

You may also specify that a filter applies to an entire set of routes based on their URI.

  1. Route::filter('admin', function()
  2. {
  3. //
  4. });
  5. Route::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.

You may also constrain pattern filters by HTTP verbs:

  1. Route::when('admin/*', 'admin', array('post'));

Filter Classes

For advanced filtering, you may wish to use a class instead of a Closure. Since filter classes are resolved out of the application IoC Container, you will be able to utilize dependency injection in these filters for greater testability.

Registering A Class Based Filter

  1. Route::filter('foo', 'FooFilter');

By default, the filter method on the FooFilter class will be called:

  1. class FooFilter {
  2. public function filter()
  3. {
  4. // Filter logic...
  5. }
  6. }

If you do not wish to use the filter method, just specify another method:

  1. Route::filter('foo', '[email protected]');

Named Routes

Named routes make referring to routes when generating redirects or URLs more convenient. You may specify a name for a route like so:

  1. Route::get('user/profile', array('as' => 'profile', function()
  2. {
  3. //
  4. }));

You may also specify route names for controller actions:

  1. Route::get('user/profile', array('as' => 'profile', 'uses' => '[email protected]'));

Now, you may use the route's name when generating URLs or redirects:

  1. $url = URL::route('profile');
  2. $redirect = Redirect::route('profile');

You may access the name of a route that is running via the currentRouteName method:

  1. $name = Route::currentRouteName();

Route Groups

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:

  1. Route::group(array('before' => 'auth'), function()
  2. {
  3. Route::get('/', function()
  4. {
  5. // Has Auth Filter
  6. });
  7. Route::get('user/profile', function()
  8. {
  9. // Has Auth Filter
  10. });
  11. });

You may also use the namespace parameter within your group array to specify all controllers within that group as being in a given namespace:

  1. Route::group(array('namespace' => 'Admin'), function()
  2. {
  3. //
  4. });

Sub-Domain Routing

Laravel routes are also able to handle wildcard sub-domains, and will pass your wildcard parameters from the domain:

Registering Sub-Domain Routes

  1. Route::group(array('domain' => '{account}.myapp.com'), function()
  2. {
  3. Route::get('user/{id}', function($account, $id)
  4. {
  5. //
  6. });
  7. });

Route Prefixing

A group of routes may be prefixed by using the prefix option in the attributes array of a group:

  1. Route::group(array('prefix' => 'admin'), function()
  2. {
  3. Route::get('user', function()
  4. {
  5. //
  6. });
  7. });

Route Model Binding

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 Route::model method to specify the model that should be used for a given parameter:

Binding A Parameter To A Model

  1. Route::model('user', 'User');

Next, define a route that contains a {user} parameter:

  1. Route::get('profile/{user}', function(User $user)
  2. {
  3. //
  4. });

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:

  1. Route::model('user', 'User', function()
  2. {
  3. throw new NotFoundHttpException;
  4. });

Sometimes you may wish to use your own resolver for route parameters. Simply use the Route::bind method:

  1. Route::bind('user', function($value, $route)
  2. {
  3. return User::where('name', $value)->first();
  4. });

Throwing 404 Errors

There are two ways to manually trigger a 404 error from a route. First, you may use the App::abort method:

  1. 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.

Routing To Controllers

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.