routing
- Basic routing
- Routing parameters
- Named route
- Route Group
- Routing model binding
- Fallback routing
- Frequency limit
- Form method forgery
- Access current route
closure, here Provides a very simple and elegant way to define routes:
Route::get('foo', function () { return 'Hello World'; });
Default routing file
All Laravel routes are defined in routing files in the routes
directory, and these files are automatically loaded by the framework. The routes/web.php
file is used to define the routes for the web
interface. The routes here will be assigned to the web
middleware group, which provides functions such as session state and CSRF protection. Routes defined in routes/api.php
are stateless and assigned the api
middleware group.
Most application builds start by defining routes in the routes/web.php
file. Routes defined in routes/web.php
can be accessed by entering the defined route URL into a browser. For example, you can enter http://your-app.dev/user
in your browser to access the following routes
Route::get('/user', 'UserController@index');
routes/api.php
file The defined route is nested into a routing group through RouteServiceProvider
. Within this route group, the URL prefix /api
is automatically added to each route in this file so you don't have to add it manually. You can modify this prefix and other route group options in the RouteServiceProvider
class.
Available routing methods
The router allows you to register a route that can respond to any HTTP request:
Route::get($uri, $callback); Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback);
Sometimes you may need to register a route that can respond to any HTTP request: To respond to multiple HTTP requests, you can use the match
method, or you can use the any
method to register a route that responds to all HTTP requests:
Route::match(['get', 'post'], '/', function () { // }); Route::any('foo', function () { // });
CSRF protection
points to the POST
, PUT
or DELETE
defined in the web
routing file Any HTML form routed should contain a CSRF token field, otherwise the request will be rejected. You can read more about CSRF in the CSRF documentation:
<form method="POST" action="/profile"> @csrf ... </form>
Redirect Route
If you want to define To redirect a route to another URI, use the Route::redirect
method. This method can quickly implement redirection without having to define a complete route or controller:
Route::redirect('/here', '/there');
Route::redirect
The default status code 302## will be returned # . You can customize the return code through the third parameter:
Route::redirect('/here', '/there', 301);You can also use the
Route::permanentRedirect method to return the
301 status code:
Route::permanentRedirect('/here', '/there');
View routing
If your route only needs to return a view, you can use the Route::view
method. It's just as convenient as redirect
and doesn't require defining full routes or controllers. view
The method has three parameters, the first of which is a required parameter and is the URI containing the view name. The second and required parameter is the name of the view that needs to be rendered. The third parameter is an optional parameter. You can pass in an array, and the data in the array will be passed to the view:
Route::view('/welcome', 'welcome'); Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
Route Parameters
Required Parameters
Of course, sometimes you need to capture some URL fragments in the route. For example, to capture the user's ID from the URL, you can do this by defining route parameters:
Route::get('user/{id}', function ($id) { return 'User '.$id; });
You can also define multiple parameters in the route as needed:
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) { // });
The parameters of the route are usually will be placed within {}
, and parameter names can only be letters. At the same time, routing parameters cannot contain -
symbols. Underlines (_
) can be used if necessary. replace. Route parameters will be injected into route callbacks or controllers in order, regardless of the parameter names of the callbacks or controllers.
Optional Parameters
Sometimes, you may need to specify a routing parameter, but you want this parameter to be available Chosen. You can add the ?
tag after the parameter to achieve this, but the premise is to ensure that the corresponding variable of the route has a default value
Route::get('user/{name?}', function ($name = null) { return $name; }); Route::get('user/{name?}', function ($name = 'John') { return $name; });
Regular Expression Constraints
You can constrain the format of route parameters using the where
method on a route instance. where
The method accepts a parameter name and a regular expression that defines 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 constraint
If you want a specific Routing parameters all follow the constraints of the same regular expression. Use the pattern
method to define these patterns in the boot
method of RouteServiceProvider
:
/** * 定义你的路由模型绑定, pattern 过滤器等。 * * @return void */ public function boot(){ Route::pattern('id', '[0-9]+'); parent::boot(); }
Once defined, these rules will be automatically applied to all routes using this parameter name:
Route::get('user/{id}', function ($id) { // 只有在 id 为数字时才执行。 });
Encoded forward slash characters
Laravel routing components allow All characters except /
. You must explicitly allow /
to be part of the placeholder using a where
conditional regex:
Route::get('search/{search}', function ($search) { return $search; })->where('search', '.*');
Note: encoded forward slash character only in the last It is supported in routing segments.
Route naming
Route naming can easily generate URLs or redirects for specified routes. You can specify the route name by chaining the name
method on the route definition:
Route::get('user/profile', function () { // })->name('profile');
You can also specify the route name of the controller action:
Route::get('user/profile', 'UserProfileController@show')->name('profile');
Generate the URL of the specified route
After specifying a name for the route, you can use the global auxiliary function route
to generate a link or redirect to the route:
// 生成 URL... $url = route('profile'); // 生成重定向... return redirect()->route('profile');
If it is a named route with defined parameters, you can pass the parameters as the second parameter of the route
function, and the specified parameters will be automatically inserted into the corresponding position in the URL:
Route::get('user/{id}/profile', function ($id) { // })->name('profile'); $url = route('profile', ['id' => 1]);
Check the current route
If you want to determine whether the current request points to a certain route, you can call the named
method on the routing instance. For example, you can check the current route name in the routing middleware:
/** * 处理一次请求。 * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next){ if ($request->route()->named('profile')) { // } return $next($request); }
routing group
routing group allowed You share route properties, such as middleware or namespaces, across a large number of routes without defining these properties individually for each route. Shared attributes should be passed into the first parameter of the Route::group
method in the form of an array.
Middleware
To assign middleware to all routes in a routing group, you can call it before groupmiddleware
method, middleware will be run in the order they are listed in the array:
Route::middleware(['first', 'second'])->group(function () { Route::get('/', function () { // // 使用 first 和 second 中间件 }); Route::get('user/profile', function () { // // 使用 first 和 second 中间件 }); });
Namespace
Another common use case is to assign the same PHP namespace to all controllers in a routing group using the namespace
method:
Route::namespace('Admin')->group(function () { // 在 "App\Http\Controllers\Admin" 命名空间下的控制器 });
Remember that by default Next, RouteServiceProvider
will introduce your route file in the namespace group, allowing you to register controller routes without specifying the complete App\Http\Controllers
namespace prefix. Therefore, you only need to specify the part after the namespace App\Http\Controllers
.
Subdomain name routing
Routing groups can also be used to handle subdomain names. Subdomains can be assigned route parameters just like route URIs, allowing you to get a portion of the subdomain as parameters for a route or controller. You can call the domain
method before group to specify a subdomain name:
Route::domain('{account}.myapp.com')->group(function () { Route::get('user/{id}', function ($account, $id) { // }); });
Routing prefix
You can use the prefix
method to add a prefix to the URL given in the routing group. For example, you can prefix the URIs of all routes in the group with admin:
Route::prefix('admin')->group(function () { Route::get('users', function () { // 匹配包含 "/admin/users" 的 URL }); });
Route name prefix
The name method can be used to add a given string to each route name in the routing group. For example, you might want to prefix the names of all group routes with "admin." The given string is exactly the same as the specified route name prefix, so we will make sure to provide the trailing .
characters in the prefix:
Route::name('admin.')->group(function () { Route::get('users', function () { // 指定路由名为 "admin.users"... })->name('users');});
Route model binding
When injecting a model ID into a route or controller behavior, you need to query the model corresponding to this ID. Laravel provides a way for route model binding to directly and automatically inject model instances into routes. For example, instead of injecting the user's ID, you can inject the entire User
model instance that matches a given ID.
Implicit binding
Laravel will automatically parse the type hints defined in routes or controller actions. The variable name matches the route segment name of the Eloquent model. For example:
Route::get('api/users/{user}', function (App\User $user) { return $user->email; });
In this example, since the $user
variable is type-hinted to the Eloquent model App\User
, the variable name is the same as the in the URI. {user}
matches, so Laravel automatically injects a user model instance that matches the ID passed in the request URI. If the corresponding model instance cannot be found in the database, a 404 exception will be automatically generated.
Custom key name
If you want model binding to use a database other than id
when retrieving the given model class Field, you can override the getRouteKeyName
method on the Eloquent model:
/** * 获取该模型的路由的自定义键名。 * * @return string */ public function getRouteKeyName(){ return 'slug'; }##Explicit Binding To register an explicit binding, use the router's
model method to specify the class for the given parameter. Define these explicit model bindings within the
boot method in the
RouteServiceProvider class:
public function boot(){ parent::boot(); Route::model('user', App\User::class); }Next, define a parameter containing
{user} Route for:
Route::get('profile/{user}', function (App\User $user) { // });Because we have bound all
{user} parameters to the
App\User model, the
User instance will be Inject this route. For example, a request for
profile/1 will inject the
User instance with ID 1 in the database.
Custom logic parsing
If you want to use custom parsing logic, use the Route::bind
method. The closure
passed to the bind
method will accept the value corresponding to the braces in the URI and return an instance of the class you want to inject in the route:
/** * 启动应用服务。 * * @return void */ public function boot(){ parent::boot(); Route::bind('user', function ($value) { return App\User::where('name', $value)->first() ?? abort(404); }); }
Alternatively, you can override the resolveRouteBinding
method on the Eloquent model. This method accepts the value corresponding to the braces in the URI and returns an instance of the class you want to inject in the route:
/** * 检索绑定值的模型。 * * @param mixed $value * @return \Illuminate\Database\Eloquent\Model|null */ public function resolveRouteBinding($value){ return $this->where('name', $value)->first() ?? abort(404); }
Fallback Route
Using the Route::fallback
method, you can define a route that is executed when no other route matches the incoming request. Typically, unhandled requests are automatically rendered with a "404" page via the application's exception handler. However, because you can define fallback
routes in the routes/web.php
file, all middleware from web
middleware will be applied to the route. Of course, you can add additional middleware to this route as needed:
Route::fallback(function () { // });
{note} The fallback route should always be the last route registered by your application.
Access Control
Laravel includes a middleware for controlling application access to routes. If you want to use it, assign the throttle
middleware to a route or a route group. throttle
The middleware will receive two parameters, which determine the maximum number of requests that can be made within a given number of minutes. For example, let's specify a routing group that is authenticated and that users access no more than 60 times per minute:
Route::middleware('auth:api', 'throttle:60,1')->group(function () { Route::get('/user', function () { // }); });
Dynamic Access Control
You can configure The User
attribute of the model specifies the maximum value for dynamic requests. For example, if your User
model contains the rate_limit
attribute, you can pass the attribute name to the throttle
middleware so that it is used to calculate the maximum number of requests:
Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () { Route::get('/user', function () { // }); });##Form method forgeryHTML form does not support
PUT,
PATCH or
DELETE behavior. So when you want to call a route that defines the
PUT,
PATCH, or
DELETE behavior from an HTML form, you will need to add a hidden # to the form. ##_method
Enter the tag. Use the value of the _method
field as the HTTP request method:
You can also use the <form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
template directive to generate _method
Input: <form action="/foo/bar" method="POST">
@method('PUT')
@csrf
</form>
Accessing the current route
You can use the current
, currentRouteName
, and currentRouteAction
methods on the Route facade to access the processes that handle incoming requests. Routing information:
$route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();
If you want to know all the accessible methods, you can check the API documentation to learn about the base classes of Route facade and Route instance.