Laravel Admin and User login with middleware

If you have developed or developing such app which has Admin and user role like E-commerce app so you must have needed to create a bridge between Admin and the user to secure your application. In this article, I am going to tell you how can you make your app Admin panel secure with middleware so that a user could not get access.

We need to create an Admin middleware to authenticate admin. We need not create middleware for the users.

Create a middleware

Create a middleware and name it Admin. Run the following command in the root of your application.

php artisan make:middleware Admin

In app\Http\Middleware Admin.php file will be created, open it in your editor.

namespace App\Http\Middleware;

use Closure;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Replace the code with the following code:

namespace App\Http\Middleware;

use Closure;
use Auth;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // isAdmin() function defined in User model
        if ( Auth::check() && Auth::user()->isAdmin() )
        {
            return $next($request);
        }

        return redirect( route('admin.home') );
    }
}

Register to Kernel

Now you have to register your middleware with route middlewares, open app\Http\Kernel.php file, and add Admin middleware.

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,
        'admin' => 'App\Http\Middleware\Admin', // this line right here
    ];

This middleware will auth the user is an Admin or not. If the user is not admin it will redirect to user login page.

Create Function

Now open app\User.php model file and create isAdmin function which we have to use to authenticate user role.

public function isAdmin()
{
    return $this->role === 'admin' ? true : false;
}

Comments

Be the first to comment