@lottie
In Laravel, you can protect a route by using middleware. Middleware acts as a filter for HTTP requests entering your application. You can attach middleware to routes in your routes/web.php
file.
Here's how you can protect a route with middleware in Laravel:
- Create a new middleware using the artisan command:
php artisan make:middleware {MiddlewareName}
- Open the newly created middleware class in the app/Http/Middleware directory and add your logic to protect the route. For example, you can check if the user is authenticated before allowing them to access the route:
public function handle($request, Closure $next)
{
if (!Auth::check()) {
return redirect()->route('login');
}
return $next($request);
}
- Register the new middleware in the $routeMiddleware array in the app/Http/Kernel.php file:
protected $routeMiddleware = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'middleware_name' => AppHttpMiddlewareMiddlewareName::class,
];
- Attach the middleware to the route in the routes/web.php file by calling the middleware method on the route definition:
Route::get('protected-route', function () {
// Your route logic here
})->middleware('middleware_name');
- Now, the route is protected by the middleware, and only authenticated users will be able to access it. If a user is not authenticated, they will be redirected to the login page.
By following these steps, you can easily protect routes in Laravel using middleware.