Quick tip of the day. With routing you can specify Route::get(‘projects/{project_id}’, ‘[email protected]’); but what if you want project_id to be strictly a number?
To achieve that, you can put where() condition on any Route statement, and use regular expressions for specifying data pattern.
As an example:
// Only letters
Route::get('user/{name}', function ($name) {
//
})->where('name', '[A-Za-z]+');
// Only numbers
Route::get('user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
// A few conditions on a few parameters
Route::get('user/{id}/{name}', function ($id, $name) {
//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
Another example would be restricting some parameter to be one of a few strict values, then avoid checking it in Controller:
Route::get('/user/{user_id}/{approve_action}','[email protected]')
->where('approve_action', 'approve|decline');
If you put these conditions, then route will match only those within regular expressions, so if you enter URL /user/123 it will show 404 page.
You also can specify that some variable name would always follow a certain pattern. As an example, you want project_id in all routes to be integer. Then, you do this in app/Providers/RouteServiceProvider.php:
public function boot()
{
Route::pattern('project_id', '[0-9]+');
parent::boot();
}
Credit to: https://bit.ly/33CWlmg
Recent Comments