In this tutorial, we will explore how to implement middleware in a Laravel application. Middleware provides a convenient mechanism for inspecting and 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.
By the end of this tutorial, you will be able to:
Prerequisites: Basic knowledge of PHP and Laravel is required. Familiarity with HTTP requests and responses would be helpful.
Middleware in Laravel provides a way to wrap HTTP requests with additional behavior. It's like an onion: each layer of middleware adds or modifies behavior until the core of the request is reached.
Here are the steps to implement middleware:
Run the command php artisan make:middleware YourMiddlewareName
to create a new middleware. Replace YourMiddlewareName
with the name you want to give your middleware. This will create a new file in the app/Http/Middleware
directory.
Open the newly created file. You will see a handle
function which accepts two arguments: $request
(the incoming HTTP request instance) and $next
(a closure that you need to call when you are done with your middleware).
After writing your middleware, you need to register it in the app/Http/Kernel.php
file. You can register it either as global middleware (applies to every request) or route middleware (applied to specific routes).
If you registered your middleware as route middleware, you can assign it to routes in your routes/web.php
file using the middleware
method.
Here's an example of a simple middleware that checks if the user is authenticated:
// app/Http/Middleware/CheckIsUserAuthenticated.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckIsUserAuthenticated
{
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return redirect('login');
}
return $next($request);
}
}
In this code:
To register this middleware, add the following line to the $routeMiddleware
array in the app/Http/Kernel.php
file:
'auth' => \App\Http\Middleware\CheckIsUserAuthenticated::class,
Now you can assign this middleware to a route:
Route::get('/dashboard', function () {
// Your code here
})->middleware('auth');
We have covered:
You can continue learning by creating different types of middleware and assigning them to different routes. The Laravel documentation is a great resource for further learning.
/admin
route.Remember, practice is key in mastering Laravel middleware. Happy coding!