Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5.5 Get user details inside constructor

I am building an application with multiple user roles and actions. I did follow the official laravel doc (https://laravel.com/docs/5.5/middleware#middleware-parameters).

But in my controller's constructor (from where I call the above middleware) I am using Auth facade to get user details. I know how to use Auth facade, I had implemented it on several places inside my application. But when I use it inside the constructor it returns null (in logged in condition - I double checked that).

I implemented it like this, I have to call two controllers(since only registered users can access that page)

public function __construct()
{
    $role = Auth::user()->role;
    $this->middleware('auth');
    $this->middleware('checkRole:$role');
}

PS: I tried to initialize $role variable as protected and outside the constructor , still not working. Any suggestions will be helpful

Thank you.

like image 912
HasilT Avatar asked Sep 11 '17 17:09

HasilT


2 Answers

That's because constructors are created before middlewares,that's why its returning null.

This answer will propably solve your problems: Can't call Auth::user() on controller's constructor

like image 139
taavs Avatar answered Sep 17 '22 06:09

taavs


If you are using the same user table for both "front-end" user and "admin" & want to apply condition in admin controller's constructor.

You can use below.

auth()->user()

And in the constructor you can use below code.

public function __construct(){      
    $this->middleware(function ($request, $next) {      
        if(auth()->user()->hasRole('frontuser')){
            return redirect()->route('home')->withFlashMessage('You are not authorized to access that page.')->withFlashType('warning');
        }
        return $next($request);
    });
}

But I prefer to handle these in separate middleware class instead of writing this in the controllers constructor.

like image 29
Mahesh Yadav Avatar answered Sep 17 '22 06:09

Mahesh Yadav