This tutorial aims to teach you how to secure your Laravel application's routes using middleware. Middleware allows you to filter HTTP requests entering your application, ensuring only authorized users can access certain routes.
By the end of this tutorial, you will be able to:
- Understand what middleware is and how it works in Laravel
- Create and register a new middleware
- Secure your routes using middleware
Before starting this tutorial, you should have a basic understanding of Laravel and PHP. Familiarity with Laravel routing will be beneficial.
Middleware provides a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
To create a new middleware, use the make:middleware
Artisan command:
php artisan make:middleware CheckAge
This command will place a new CheckAge
class within your app/Http/Middleware
directory. In this middleware, we will only allow access to the route if the supplied age is greater than 200.
public function handle($request, Closure $next)
{
if ($request->age <= 200) {
return redirect('home');
}
return $next($request);
}
After creating the middleware, you need to register it in your app/Http/Kernel.php
file.
protected $routeMiddleware = [
'age' => \App\Http\Middleware\CheckAge::class,
];
Once the middleware has been defined in the HTTP kernel, you may use the middleware
method to assign middleware to a route:
Route::get('post', function () {
// Only authenticated users may enter...
})->middleware('age');
php artisan make:middleware IsAdmin
This creates a new file IsAdmin.php
in the app/Http/Middleware
directory.
public function handle($request, Closure $next)
{
if (auth()->user()->is_admin == 0) {
return redirect('home');
}
return $next($request);
}
In this example, we create a middleware that checks if the user is an admin. If they're not, they're redirected back to the 'home' page.
First, register the middleware in app/Http/Kernel.php
.
protected $routeMiddleware = [
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
Then, assign the middleware to a route.
Route::get('admin', function () {
// Only admins may enter...
})->middleware('is.admin');
In this example, only admins can access the 'admin' route.
make:middleware
Artisan command.Remember, practice is key to mastering any concept. Happy coding!