Rowayda Khayri
Rowayda Khayri

Reputation: 489

Middleware doesn't work as expected - Laravel

I want to make a middleware to protect admin routes in laravel 5.2 app. user_type isn't a field in users table in my db, but in a separate table : enter image description here

Admin's user_type_id is 4 I made this middleware :

class AdminMiddleware
{

    public function handle($request, Closure $next)
    {
        $authedUserID = Auth::id();

        $user = User::query()
                ->leftjoin('users_user_types as uut', 'uut.user_id', '=', 'users.id')
                ->where('uut.user_id',"=","$authedUserID")
                ->get(['users.*',
                        'uut.user_type_id as userType'])->first();

        if ($user['userType'] !=4)
        {

            return redirect('/home');
        }

        return $next($request);
    }
}

and put this in $routeMiddleware array in kernel.php :

'admin' => \App\Http\Middleware\AdminMiddleware::class

and this is one of admin routes I want to apply my middleware on :

Route::get('ptyadmin', 'AdminController@show')->middleware('admin');

The Problem is that when I go to this route with admin user(user_type = 4) or normal user(user_type = 1) it redirects to /home in both cases !!

Why does this happen and how can I fix it ??

Upvotes: 0

Views: 1055

Answers (2)

Rowayda Khayri
Rowayda Khayri

Reputation: 489

It works when I put jwt.auth middleware in routes.php :

Route::get('ptyadmin', 'AdminController@show')
->middleware('jwt.auth')
->middleware('admin');

instead of putting it in AdminController :

public function __construct(User $user, JWTAuth $jwtauth)

{

   $this->middleware('jwt.auth', ['except' => []]);

}

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

first method returns object

if ($user->userType !=4)

Also use selectinstead get

->select(['users.*','uut.user_type_id as userType'])->first();

Upvotes: 1

Related Questions