An example of Laravel framework implementing the function of prohibiting unlogged users from accessing pages based on middleware

  • 2021-11-13 01:04:36
  • OfStack

This article describes the Laravel framework based on middleware to prevent users from accessing the page function. Share it for your reference, as follows:

1. Generate middleware


[root@localhost MRedis]# php artisan make:middleware CheckLogin
Middleware created successfully.

2. Implement middleware in app\ http\ middleware\ CheckLogin.php


public function handle($request, Closure $next)
{
  if (!session('user')) {
    return redirect('login');
  }
  return $next($request);
}

3. Register the middleware and add the last line under app\ http\ kernel. php


protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'check.login' => \App\Http\Middleware\CheckLogin::class,  //  This 1 Row 
];

4. Use middleware (1. Be sure to put the login route outside)


Route::group(['middleware' => 'check.login'], function() { Internally, do not want unlogged users to enter the route }

5. Success

More readers interested in Laravel can check the topics of this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Laravel framework.


Related articles: