HTTP Routing

Basic Routing

You will define most of the routes for your application in the app/Http/routes.php file, which is loaded by the App\Providers\RouteServiceProvider class. The most basic Laravel routes simply accept a URI and a Closure:

  1. Route::get('/', function () {
  2. return 'Hello World';
  3. });
  4. Route::post('foo/bar', function () {
  5. return 'Hello World';
  6. });
  7. Route::put('foo/bar', function () {
  8. //
  9. });
  10. Route::delete('foo/bar', function () {
  11. //
  12. });

Registering A Route For Multiple Verbs

Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method on the Route facade:

  1. Route::match(['get', 'post'], '/', function () {
  2. return 'Hello World';
  3. });

Or, you may even register a route that responds to all HTTP verbs using the any method:

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

Generating URLs To Routes

You may generate URLs to your application's routes using the url helper:

  1. $url = url('foo');

Route Parameters

Required Parameters

Of course, sometimes you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You may do so by defining route parameters:

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

You may define as many route parameters as required by your route:

  1. Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
  2. //
  3. });

Route parameters are always encased within "curly" braces. The parameters will be passed into your route's Closure when the route is executed.

Note: Route parameters cannot contain the - character. Use an underscore (_) instead.

Optional Parameters

Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name:

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

Regular Expression Constraints

You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:

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

Global Constraints

If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method. You should define these patterns in the boot method of your RouteServiceProvider:

  1. /**
  2. * Define your route model bindings, pattern filters, etc.
  3. *
  4. * @param \Illuminate\Routing\Router $router
  5. * @return void
  6. */
  7. public function boot(Router $router)
  8. {
  9. $router->pattern('id', '[0-9]+');
  10. parent::boot($router);
  11. }

Once the pattern has been defined, it is automatically applied to all routes using that parameter name:

  1. Route::get('user/{id}', function ($id) {
  2. // Only called if {id} is numeric.
  3. });

Named Routes

Named routes allow you to conveniently generate URLs or redirects for a specific route. You may specify a name for a route using the as array key when defining the route:

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

You may also specify route names for controller actions:

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

Instead of specifying the route name in the route array definition, you may chain the name method onto the end of the route definition:

  1. Route::get('user/profile', '[email protected]')->name('profile');

Route Groups & Named Routes

If you are using route groups, you may specify an as keyword in the route group attribute array, allowing you to set a common route name prefix for all routes within the group:

  1. Route::group(['as' => 'admin::'], function () {
  2. Route::get('dashboard', ['as' => 'dashboard', function () {
  3. // Route named "admin::dashboard"
  4. }]);
  5. });

Generating URLs To Named Routes

Once you have assigned a name to a given route, you may use the route's name when generating URLs or redirects via the route function:

  1. $url = route('profile');
  2. $redirect = redirect()->route('profile');

If the route defines parameters, you may pass the parameters as the second argument to the route method. The given parameters will automatically be inserted into the URL:

  1. Route::get('user/{id}/profile', ['as' => 'profile', function ($id) {
  2. //
  3. }]);
  4. $url = route('profile', ['id' => 1]);

Route Groups

Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.

To learn more about route groups, we'll walk through several common use-cases for the feature.

Middleware

To assign middleware to all routes within a group, you may use the middleware key in the group attribute array. Middleware will be executed in the order you define this array:

  1. Route::group(['middleware' => 'auth'], function () {
  2. Route::get('/', function () {
  3. // Uses Auth Middleware
  4. });
  5. Route::get('user/profile', function () {
  6. // Uses Auth Middleware
  7. });
  8. });

Namespaces

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers. You may use the namespace parameter in your group attribute array to specify the namespace for all controllers within the group:

  1. Route::group(['namespace' => 'Admin'], function()
  2. {
  3. // Controllers Within The "App\Http\Controllers\Admin" Namespace
  4. Route::group(['namespace' => 'User'], function()
  5. {
  6. // Controllers Within The "App\Http\Controllers\Admin\User" Namespace
  7. });
  8. });

Remember, by default, the RouteServiceProvider includes your routes.php file within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, we only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace root.

Sub-Domain Routing

Route groups may also be used to route wildcard sub-domains. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain key on the group attribute array:

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

Route Prefixes

The prefix group array attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin:

  1. Route::group(['prefix' => 'admin'], function () {
  2. Route::get('users', function () {
  3. // Matches The "/admin/users" URL
  4. });
  5. });

You may also use the prefix parameter to specify common parameters for your grouped routes:

  1. Route::group(['prefix' => 'accounts/{account_id}'], function () {
  2. Route::get('detail', function ($account_id) {
  3. // Matches The accounts/{account_id}/detail URL
  4. });
  5. });

CSRF Protection

Introduction

Laravel makes it easy to protect your application from cross-site request forgeries. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of the authenticated user.

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application. To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function:

  1. <?php echo csrf_field(); ?>

The csrf_field helper function generates the following HTML:

  1. <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

Of course, using the Blade templating engine:

  1. {{ csrf_field() }}

You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken HTTP middleware will verify that the token in the request input matches the token stored in the session.

Excluding URIs From CSRF Protection

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your webhook handler route from Laravel's CSRF protection.

You may exclude URIs by adding them to the $except property of the VerifyCsrfToken middleware:

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
  4. class VerifyCsrfToken extends BaseVerifier
  5. {
  6. /**
  7. * The URIs that should be excluded from CSRF verification.
  8. *
  9. * @var array
  10. */
  11. protected $except = [
  12. 'stripe/*',
  13. ];
  14. }

X-CSRF-TOKEN

In addition to checking for the CSRF token as a POST parameter, the Laravel VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a "meta" tag:

  1. <meta name="csrf-token" content="{{ csrf_token() }}">

Once you have created the meta tag, you can instruct a library like jQuery to add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

  1. $.ajaxSetup({
  2. headers: {
  3. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  4. }
  5. });

X-XSRF-TOKEN

Laravel also stores the CSRF token in a XSRF-TOKEN cookie. You can use the cookie value to set the X-XSRF-TOKEN request header. Some JavaScript frameworks, like Angular, do this automatically for you. It is unlikely that you will need to use this value manually.

Route Model Binding

Laravel route model binding provides a convenient way to inject class instances into your routes. For example, instead of injecting a user's ID, you can inject the entire User class instance that matches the given ID.

First, use the router's model method to specify the class for a given parameter. You should define your model bindings in the RouteServiceProvider::boot method:

Binding A Parameter To A Model

  1. public function boot(Router $router)
  2. {
  3. parent::boot($router);
  4. $router->model('user', 'App\User');
  5. }

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

  1. $router->get('profile/{user}', function(App\User $user) {
  2. //
  3. });

Since we have bound the {user} parameter to the App\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 exception will be thrown automatically.

If you wish to specify your own "not found" behavior, pass a Closure as the third argument to the model method:

  1. $router->model('user', 'App\User', function() {
  2. throw new NotFoundHttpException;
  3. });

If you wish to use your own resolution logic, you should use the Route::bind method. The Closure you pass to the bind method will receive the value of the URI segment, and should return an instance of the class you want to be injected into the route:

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

Form Method Spoofing

HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:

  1. <form action="/foo/bar" method="POST">
  2. <input type="hidden" name="_method" value="PUT">
  3. <input type="hidden" name="_token" value="{{ csrf_token() }}">
  4. </form>

To generate the hidden input field _method, you may also use the method_field helper function:

  1. <?php echo method_field('PUT'); ?>

Of course, using the Blade templating engine:

  1. {{ method_field('PUT') }}

Throwing 404 Errors

There are two ways to manually trigger a 404 error from a route. First, you may use the abort helper. The abort helper simply throws a Symfony\Component\HttpFoundation\Exception\HttpException with the specified status code:

  1. abort(404);

Secondly, you may manually 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.