Enrutado HTTP

Enrutado básico

Definirá la mayoría de las rutas para su aplicación en el archivo app/Http/routes.php, que se carga a través de la clase App\Providers\RouteServiceProvider. Las rutas más básicas Laravel simplemente aceptan una URI y un Closure:

Route::get('/', function () {
    return 'Hello World';
});

Route::post('foo/bar', function () {
    return 'Hello World';
});

Route::put('foo/bar', function () {
    //
});

Route::delete('foo/bar', function () {
    //
});

Registrar una ruta para múltiples verbos

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:

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

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

Route::any('foo', function () {
    return 'Hello World';
});

Generating URLs To Routes

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

$url = url('foo');

Parámetros de ruta

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:

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

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

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

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:

Route::get('user/{name?}', function ($name = null) {
    return $name;
});

Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});

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:

Route::get('user/{name}', function ($name) {
    //
})
->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {
    //
})
->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {
    //
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Global Constraints

Si le gustaría que un parámetro de ruta esté restringido por una expresión regular, puede usar el método pattern. Debería definir esos patrones en el método boot de su RouteServiceProvider:

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @param  \Illuminate\Routing\Router  $router
 * @return void
 */
public function boot(Router $router)
{
    $router->pattern('id', '[0-9]+');

    parent::boot($router);
}

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

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

Rutas con nombres

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:

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

Puedes además especificar nombres de ruta para acciones de un controlador:

Route::get('user/profile', [
    'as' => 'profile', 'uses' => 'UserController@showProfile'
]);

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:

Route::group(['as' => 'admin::'], function () {
    Route::get('dashboard', ['as' => 'dashboard', function () {
        // Route named "admin::dashboard"
    }]);
});

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:

$url = route('profile');

$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:

Route::get('user/{id}/profile', ['as' => 'profile', function ($id) {
    //
}]);

$url = route('profile', ['id' => 1]);

Grupos de rutas

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 routes. 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:

Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function () {
        // Uses Auth Middleware
    });

    Route::get('user/profile', function () {
        // Uses Auth Middleware
    });
});

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:

Route::group(['namespace' => 'Admin'], function()
{
    // Controllers Within The "App\Http\Controllers\Admin" Namespace

    Route::group(['namespace' => 'User'], function()
    {
        // Controllers Within The "App\Http\Controllers\Admin\User" Namespace
    });
});

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.

Rutas de sub-dominio

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:

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

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:

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

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

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

Protección CSRF

Introducción

Laravel hace simple la protección de tu aplicación contra cross-site request forgeries. Cross-site request forgeries son un tipo de exploit maliciosos a través del cual se ejecutan comandos no autorizados en nombre del usuario que se ha autenticado.

Laravel automáticamente genera un "token" CSRF para cada sesión de usuario activo manejado por la aplicación. Este token es usado para verificar que el usuario autenticado es el que actualmente está haciendo la petición a la aplicación. To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function:

<?php echo csrf_field(); ?>

The csrf_field helper function generates the following HTML:

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

Of course, using the Blade templating engine:

{!! csrf_field() !!}

No necesita verificar manualmente el token CSRF en las peticiones POST, PUT o DELETE. The VerifyCsrfToken HTTP middleware will verify 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:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
    ];
}

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:

<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:

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

X-XSRF-TOKEN

Laravel también almacena el token CSRF en una cookie XSRF-TOKEN. Puede usar el valor de la cookie para establecer la cabecera de la petición X-XSRF-TOKEN. Some JavaScript frameworks, like Angular, do this automatically for you. It is unlikely that you will need to use this value manually.

Form Method Spoofing

Los formularios HTML no soportan las acciones PUT, PATCH o DELETE. Por tanto, cuando defina las rutas PUT, PATCH o DELETE que son llamadas desde un formulario HTML, necesitará agregar un campo oculto _method al formulario. The value sent with the _method field will be used as the HTTP request method:

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

Lanzando errores 404

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:

abort(404);

En segundo lugar, puede lanzar manualmente una instancia de 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.