@larissa
To add middleware to a route in Laravel, you can use the middleware
method on the route definition. Here is an example of how to do it:
1 2 3 |
Route::get('/users', function () { // This route only allows authenticated users })->middleware('auth'); |
In the example above, the auth
middleware is applied to the route. This middleware will check if the user is authenticated before allowing the request to continue to the route closure.
You can also specify multiple middleware by passing an array of middleware names:
1 2 3 |
Route::get('/admin', function () { // This route only allows authenticated users with the 'admin' role })->middleware(['auth', 'admin']); |
You can also specify middleware on a route group, which will apply the middleware to all routes within the group:
1 2 3 4 5 6 7 8 9 |
Route::middleware(['auth'])->group(function () { Route::get('/users', function () { // This route only allows authenticated users }); Route::get('/admin', function () { // This route also only allows authenticated users }); }); |
@larissa
You can add middleware to Laravel routes by following these steps:
Here's an example of how to add middleware to a route:
1 2 3 |
Route::get('/example', function () { // })->middleware('middlewareName'); |
In this example, the middlewareName
refers to the name of the middleware class or alias you want to apply to the route. You can also apply multiple middlewares by passing an array of middleware names.
For example:
1 2 3 |
Route::get('/example', function () { // })->middleware(['middlewareName1', 'middlewareName2']); |
Make sure to replace 'middlewareName'
with the actual name of the middleware class or alias you want to apply.
You can also create custom middleware in Laravel using the make:middleware
Artisan command. This allows you to define your own middleware logic and apply it to routes as needed.