Laravel allows us to pass a condition while defining a route. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained of this route.

In this tutorial, we will see how to use regular expression while defining a route and we will see an example of a Laravel route where condition.

Sometimes we need to filter requested input and we can sanitize it in our controller with a request()->validate() helper or we can use a custom form request class to validate input data. But we can sanitize the requested input with where condition with the route. If you do not know Laravel route where condition, then this tutorial will of course help you.

laravel-route-where

See the example of how to use the where condition in the Laravel route:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('/user/{name}', function (string $name) {
    // ...
})->where('name', '[A-Za-z]+');
 
Route::get('/user/{id}', function (string $id) {
    // ...
})->where('id', '[0-9]+');
 
Route::get('/user/{id}/{name}', function (string $id, string $name) {
    // ...
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

 

We can define the route like that also:

Route::get('/user/{id}/{name}', function (string $id, string $name) {
    // ...
})->whereNumber('id')->whereAlpha('name');
 
Route::get('/user/{name}', function (string $name) {
    // ...
})->whereAlphaNumeric('name');
 
Route::get('/user/{id}', function (string $id) {
    // ...
})->whereUuid('id');
 
Route::get('/user/{id}', function (string $id) {
    //
})->whereUlid('id');
 
Route::get('/category/{category}', function (string $category) {
    // ...
})->whereIn('category', ['movie', 'song', 'painting']);

 

Read also: Laravel 10 Route Model Binding With UUID Example

 

Conclusion

I have tried to discuss the clear concept of how to use where conditions in the Laravel route. Hope this Laravel route where the condition example tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel routing