Entrance of Laravel application: Parameters, naming and grouping of routing series


Routing parameters

Required parameter

Sometimes we need to get the URI request parameters in the route. For example, if you want to get the user ID from the URL, you need to define the routing parameters in the following way:

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

So we can access http://blog.dev/user/1 , you will get the following output:

 User 1

You can define multiple route parameters in the route as needed:

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

According to the above example, the route parameters need to pass the curly braces {} These parameters will be passed to the route closure when the route is executed. Routing parameter name cannot contain - Character, can be used if necessary _ Substitution. For example, if a route parameter is defined as {post-id} The access route will report an error, which should be modified to {post_id} Only then. The route parameters injected into the route callback/controller depend on their order and are independent of the callback/controller name.

Optional parameters

If there are required parameters, there are optional parameters. You can add a ? Mark. In this case, you need to specify a default value for the corresponding variable. When the corresponding routing parameter is empty, the default value is used:

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

If the defined route is the following, access http://blog.dev/user Will return John

Regular constraint

You can route through the where Method to constrain the format of routing parameters. where Method receives a parameter name and a regular expression to define how the parameter is constrained:

 Route::get('user/{name}', function ($name) { //Name must be a letter and cannot be empty })->where('name', '[A-Za-z]+'); Route::get('user/{id}', function ($id) { //ID must be a number })->where('id', '[0-9]+'); Route::get('user/{id}/{name}', function ($id, $name) { //Specify the data format of both ID and name })->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Another advantage of using regular constraints is to avoid user/{id} and user/{name} Confusion.

Global constraints

If you want the routing parameters to be constrained by a given regular expression in the global scope, you can use pattern method. Need to be in RouteServiceProvider Class boot Method:

 /** *Define routing model binding, mode filter, etc * * @param  \Illuminate\Routing\Router  $router * @return void * @translator   https://xueyuanjun.com */ public function boot() { Route::pattern('id', '[0-9]+'); parent::boot(); }

Once the mode is defined, it will be automatically applied to all routes containing the parameter name:

 Route::get('user/{id}', function ($id) { //Only when {id} is a number can it be called });

In addition, this mode can also be applied to the following routing parameters:

 Route::get('post/{id}', function ($id) { //Only when {id} is a number can it be called }); Route::get(`product/{id}', function ($id) { //Only when {id} is a number can it be called });

Obviously, this method makes the code more concise, and also brings convenience for us to implement uniform constraints on the same parameter.

Named Routes

Named routes facilitate the generation of URLs or redirects, and are simple to implement. They are used after the route definition name Method chain to define the name of the route:

 Route::get('user/profile', function () { //Generate URL by route name return 'my url: ' . route('profile'); })->name('profile');

You can also specify routing names for controller actions:

 Route::get('user/profile', ' UserController@showProfile ')->name('profile');

In this way, we can define redirection in the following ways:

 Route::get('redirect', function() { //Redirect by route name return redirect()->route('profile'); });

Generate URLs for named routes

As shown in the above code, after assigning a name to a given route, you can use the auxiliary function route Generate a URL for this named route:

 $url = route('profile');

If the named route defines a parameter, it can be passed as the second parameter to route Function. The given routing parameters will be automatically inserted into the URL:

 Route::get('user/{id}/profile', function ($id) { $url = route('profile', ['id' => $id]); return $url; })->name('profile');

So when we visit http://blog.dev/user/123/profile Page output content is also http://blog.dev/user/123/profile

Check the current route

If you want to determine whether the current request is routed to a given named route, you can use the named For example, you can check the current route name from the routing middleware:

 /** *Process input request * * @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

The purpose of routing packets is to let us share the same routing attributes, such as middleware and namespace, among multiple routes. In this way, when we have defined a large number of routes, we do not need to define attributes for each route separately. The shared attribute is passed as the first parameter to the Route::group method.

middleware

To assign middleware to all routes defined in a routing packet, you can use it before defining the packet middleware method. Middleware will be executed in the order defined in the array:

 Route::middleware(['first', 'second'])->group(function () { Route::get('/', function () { // Uses first & second Middleware }); Route::get('user/profile', function () { // Uses first & second Middleware }); });

As for the use of middleware, we will give an example demonstration when we talk about middleware separately later. Here we will first understand how to use it in this way.

Namespace

Another common example of routing packets is the use of namespace Method to assign the same PHP namespace to multiple controllers under the group:

 Route::namespace('Admin')->group(function () { // Controllers Within The "App\Http\Controllers\Admin" Namespace });

By default, RouteServiceProvider Introduce all routing files under a namespace group, and specify that the default namespace of all controller classes is App\Http\Controllers Therefore, we only need to specify the namespace when defining the controller App\Http\Controllers The following part is enough.

The namespace will be demonstrated in detail when we talk about the controller separately. Here, we need to understand the usage first.

Subdomain routing

Routing packets can also be used to process sub domain routing, and sub domain names can be assigned to routing parameters like URIs, thus allowing the part of the captured sub domain name to be used for routing or controller. The sub domain name can be called before defining the packet domain Method to specify:

 Route::domain('{account}.blog.dev')->group(function () { Route::get('user/{id}', function ($account, $id) { return 'This is ' . $account . ' page of User ' . $id; }); });

For example, we set the member subdomain name to account.blog.dev , then you can pass http://account.blog.dev/user/1 Access user ID is one 's member information:

 This is account page of User 1

Routing prefix

prefix The method can be used to add a given URI prefix for each route in the group. For example, you can add all route URIs in the group admin Prefix:

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

So we can get through http://blog.dev/admin/users Access route.


give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: Entrance to the Larravel application: Basic Introduction to Routing Series

>>Next: Entrance to Larravel application: Routing model binding of routing series