Routing variable rules


Routing variable rules

To master routing rules, you should have basic knowledge of regular expressions

The default variable rule setting of the system is \w, which will only match letters, numbers, Chinese and underline characters, and will not match special symbols and other characters. You need to define variable rules or adjust the default variable rules.

You can customize the default variable rules in the routing configuration file, such as adding matching of underscore characters:

'default_route_pattern'	=>	'[\w\-]+',

Supports specifying variable rules in rule routing, which makes up for the inability to limit dynamic variables. Specific type issues, and supports global rule settings. The usage is as follows:

Local variable rules

Local variable rules are only valid in the current route:

// 定义GET请求路由规则 并设置name变量规则
Route::get('new/:name', 'News/read')
    ->pattern(['name' => '[\w|\-]+']);

No need to add ^ at the beginning Or add $ at the end. Mode modifiers are not supported and the system will add them automatically.

Global variable rules

Set global variable rules, all routes are valid:

// 支持批量添加
Route::pattern([
    'name' => '\w+',
    'id'   => '\d+',
]);

Combined variables

If your routing rules are special, you can use combination variables when defining routes.

For example

Route::get('item-<name>-<id>', 'product/detail')
    ->pattern(['name' => '\w+', 'id' => '\d+']);

The advantage of combining variables is that there are no fixed separators in routing rules. You can combine the required variable rules and separators at will. For example, the routing rules can be changed to the following Support:

Route::get('item<name><id>', 'product/detail')
    ->pattern(['name' => '[a-zA-Z]+', 'id' => '\d+']);
Route::get('item@<name>-<id>', 'product/detail')
    ->pattern(['name' => '\w+', 'id' => '\d+']);

If you need to use optional variables when using combined variables, you can use the following method:

Route::get('item-<name><id?>', 'product/detail')
    ->pattern(['name' => '[a-zA-Z]+', 'id' => '\d+']);

Dynamic routing

You can pass the variables in the routing rules into the routing address to implement a dynamic routing. For example:

// 定义动态路由
Route::get('hello/:name', 'index/:name/hello');

The value of the name variable is passed in as the routing address.

Variables in dynamic routing also support combined variables and assembly, for example:

Route::get('item-<name>-<id>', 'product_:name/detail')
    ->pattern(['name' => '\w+', 'id' => '\d+']);