Sid
Sid

Reputation: 5833

laravel middleware not working as expected

I have created two middleware in order to protect user route and admin routes

my UserMiddleware looks like this

<?php

namespace App\Http\Middleware;
use Auth;
use Closure;

class UserMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::user()->hasRole('user')) {
            return $next($request);
        }
        throw new \Exception("Unauthorized");
    }
}

and this is my Adminmiddleware

<?php

namespace App\Http\Middleware;
use Auth;
use Closure;
use App\Role;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::user()->hasRole('admin')) {
            return $next($request);
        }
        throw new \Exception("Unauthorized");
    }
}

Now what i want is when admin is logging in, i want a admin dashboard to open and when user is logging in, i want user dashboard to open, but now, it is redirecting me only to the admin route only when I try to login from user and admin, I have my user protected routes like this

Route::group(['middleware' => 'auth', 'user'], function () {
    //all user routes
});

and admin protected routes

Route::group(['middleware' => 'auth', 'admin'], function () {
    //all admin routes
});

and in my kernel.php, I have also added

'admin' => \App\Http\Middleware\AdminMiddleware::class,
'user' => \App\Http\Middleware\UserMiddleware::class,

and this is how I have validated a login in my controller

$loginData = array(
    'email' => Input::get('email'),
    'password' => Input::get('password'),
    'confirmed' => 1
);

/*
 * Checking against the record in database whether the email and password is valid
 * Or the record exists in the database
 */
if (Auth::validate($loginData)) {
    if (Auth::attempt($loginData)) {
            return Redirect::intended('dashboard');
    }
}
else {
    // if any error send back with message.
    Session::flash('error', 'Invalid Email/Password Combination');
    return Redirect::to('login');
}

how can I make my middleware work and show admin dashboard when admin logs and user dashboard when user logs in. This has created a big problem for me.

Upvotes: 1

Views: 5453

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

First of all, if you want to show unauthorized users the login form, your middleware should redirect to login form. In order to have it, replace

throw new \Exception("Unauthorized");

with

return redirect(route('login'));

Secondly, your login controller should redirect users to the dashboard corresponding to their roles. In order to get the proper redirect, replace

if (Auth::attempt($loginData)) {
  return Redirect::intended('dashboard');
}

with

if (Auth::attempt($loginData)) {
  return Redirect::intended(Auth::user()->hasRole('admin') ? 'admin_dashboard' : 'user_dashboard');
}

The last issue is that you apply middleware to your routes incorrectly. If you want to apply multiple middlewares, you need to pass a list as middleware paramter. Replace

['middleware' => 'auth', 'user']

with

['middleware' => ['auth', 'user']]

Upvotes: 2

Related Questions