In this tutorial, I will show you laravel route global constraints example. You know that we can validate our route parameters using regular expressions. Did you know that we can do it using global constraints? If you don't know that, this example is for you.
Sometimes you would like a route parameter to always be constrained by a given regular expression, in this case, you may use the pattern
method.
App\Providers\RouteServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
Route::pattern('id', '[0-9]+');
}
}
Now the pattern has been defined, it is automatically applied to all routes using that parameter name:
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/user/{id}', function ($id) {
// Only executed if {id} is numeric...
});
Hope it can help you.