1. Basic Routing
The most basic Laravel route receives only one URI and one closure, and provides a very simple and elegant way to define the route:
Route::get (' foo ', function () { return ' Hello World ';});
Default route file
All laravel routes are defined in routes
a routing file that is located in the directory, which is loaded automatically through the framework. The routes/web.php
file defines the web
routing of the interface, which is assigned to the Web Middleware group to provide functions such as session and CSRF protection. routes/api.php
the routes in are stateless and are assigned to the api
middleware group.
For most applications, routing is defined from the beginning of the routes/web.php
file.
An efficient routing method
We can register the route to respond to any HTTP request:
Route::get ($uri, $callback); Route::p ost ($uri, $callback); Route::p ut ($uri, $callback); Route::p atch ($uri, $callback); Route::d elete ($uri, $callback); Route::options ($uri, $callback);
Sometimes it is also necessary to register a route to respond to multiple HTTP requests-this can be done by match
means of methods. Alternatively, you can use any
a method to register a route to respond to all HTTP requests:
Route::match ([' Get ', ' post '], '/', function () { //}); Route::any (' foo ', function () { //});
CSRF Protection
web
all HTML forms in a routing file that PUT
are requested in or are included in POST
DELETE
a CSRF token field, otherwise the request is rejected. For more details on CSRF, refer to its documentation:
<form method= "POST" action= "/profile" > {{Csrf_field ()}} ...</form>
2. Routing Parameters
Required Parameters
Sometimes we need to capture the URI fragment in the route. For example, to capture a user ID from a URL, you need to define the route parameters in the following ways:
Route::get (' User/{id} ', function ($id) { return ' user '. $id;});
You can define multiple route parameters in a route as needed:
Route::get (' posts/{post}/comments/{comment} ', function ($postId, $commentId) { //});
Route parameters are always wrapped in curly braces, which are passed to the closed packet of the route when the route is executed.
Note: Routing parameters cannot contain -
characters and can be substituted if needed _
.
Optional Parameters
Sometimes it may be necessary to specify optional route parameters, which can be implemented by adding a tag to the parameter name ?
, in which case a default value is given to the corresponding variable:
Route::get (' user/{name} ', function ($name = null) { return $name;}); Route::get (' user/{name} ', function ($name = ' John ') { return $name;});
3. Named Routes
Named routes provide the convenience of generating URLs or redirects. The implementation is also simple, using the method chain after the route definition name
to implement:
Route::get (' User/profile ', function () { //})->name (' profile ');
You can also specify a route name for the controller action:
Route::get (' User/profile ', ' [email protected] ')->name (' profile ');
To generate a URL for a named route
After assigning a name to a given route, you can route
generate a URL for that named route through an auxiliary function:
$url = route (' profile '), $redirect = Redirect ()->route (' profile ');
If a named route defines a parameter, you can pass the parameter to the function as the second argument route
. The given route parameters are automatically inserted into the URL:
Route::get (' User/{id}/profile ', [' as ' + ' profile ', function ($id) { //}]); $url = route ("Profile", [' id ' = 1]) ;
4. Routing Groups
Routing groups allow us to share routing attributes across multiple routes, such as middleware and namespaces, so that we don't have to define attributes for each route individually. The shared property is passed to the method as the first parameter in the form of an array Route::group
.
Middleware
To assign middleware to all routes defined in the routing group, you can use them in the group attribute array middleware
. The middleware will execute sequentially in the order defined in the array:
Route::group ([' middleware ' = ' auth '], function () { route::get ('/', function () { //using AUTH middleware });
route::get (' User/profile ', function () { //using Auth middleware });
name Space
Another common example is that routing groups are assigned to multiple controllers under the same PHP namespace, and can be used in a grouped attribute array namespace
to specify the common namespaces for all controllers in the group:
Route::group ([' namespace ' = ' Admin '], function () { //Controller in "App\http\controllers\admin" namespace under the Route:: Group ([' namespace ' = ' User '], function () { //Controller in "App\http\controllers\admin\user" namespace });
By default, RouteServiceProvider
you introduce your routing file and specify the default namespace under which all the controller classes are located App\Http\Controllers
, so we only need to specify the part after the namespace when we define it App\Http\Controllers
.
sub-domain Routing
Routing groups can also be used for sub-domain routing wildcards, which can be assigned to route parameters like URIs, allowing the capture of sub-domain names to be used for routing or controllers, and subdomains can be specified through the array of group attributes domain
:
Route::group ([' domain ' = ' {account}.myapp.com '], function () { route::get (' user/{id} ', Function ($account, $ ID) { // });
Route prefixes
Group Properties prefix
can be used to add a given URI prefix for each route in a group, for example, you can prefix all route URIs admin
:
Route::group ([' prefix ' = ' admin '], function () { route::get (' Users ', function () { //Match "/admin/users" url
});
5.
Routing model Bindings
When injecting a model ID into a routing or controller action, it is often necessary to query the database to obtain the corresponding model data. Laravel Routing model binding makes it easy to inject model instances into routes, for example, you can inject an entire class instance that matches a given ID User
into a route instead of injecting a user ID directly.
Implicit binding
Laravel automatically resolves the eloquent model type declarations defined in the routing or Controller action (variable name matching route fragment), for example:
Route::get (' Api/users/{user} ', function (App\user $user) { return $user->email;});
In this example, because the type declares the eloquent model App\User
, the corresponding variable name $user
matches the route fragment {user}
, so that Laravel automatically injects the user model instance corresponding to the ID passed in the request URI.
If the corresponding model instance is not found in the database, an HTTP 404 response is generated automatically.
Custom Key Name
If you want implicit model binding to use other fields of the data table, you can override the methods of the eloquent model class getRouteKeyName
:
/** * Get The route key for the model. * * @return string */public function Getroutekeyname () { return ' slug ';}
Explicit Binding
To register an explicit binding, you need to use a route model
method to specify the binding class for the given parameter. Model bindings should be defined in the RouteServiceProvider::boot
method:
Binding parameters to a model
Public Function boot () { parent::boot (); $router->model (' user ', ' App\user ');}
Next, define a route that contains {user}
the parameters:
$router->get (' Profile/{user} ', function (App\user $user) { //});
Since we have bound the {user}
parameters to App\User
the model, the User instance is injected into the route. Therefore, if the request URL is profile/1
, it injects a user instance with an ID of 1.
If the matching model instance does not exist in the database, the HTTP 404 response is automatically generated and returned.
Custom parsing logic
If you want to use a custom parsing logic that requires a Route::bind
method, the closure passed to bind
the method gets the value in the URI request parameter, and returns the class instance that you want to inject in the route:
$router->bind (' User ', function ($value) { return app\user::where (' name ', $value)->first ();});
6. Form Method Forgery
HTML forms do not support PUT
PATCH
or DELETE
request methods, so when defining PUT
, PATCH
or DELETE
routing, you need to add a hidden _method
field to the form whose value is used as the HTTP request method for that form:
<form action= "/foo/bar" method= "POST" > <input type= "hidden" name= "_method" value= "PUT" > < Input type= "hidden" name= "_token" value= "{{Csrf_token ()}}" ></form>
You can also use auxiliary functions for method_field
this purpose:
{{Method_field (' PUT ')}}
7. Access the current route
You can use the Route
façade's current
, currentRouteName
and currentRouteAction
methods to access the routing information that handles the current input request:
$route = Route::current (); $name = Route::currentroutename (); $action = Route::currentrouteaction ();
Refer to the API documentation to learn more about the routing façade underlying classes and the more available methods for route instances.
HTTP Layer--routing