Laravel Auth not working in Construct

Updated at 26-Aug-2022, By samar

Laravel Auth not working in Construct

Through many examples, we will learn how to resolve the "Laravel Auth not working in Construct".

How can i get the logged in user details using Auth in the construct method in Laravel. I am not getting the logged in user details after using `Auth::user()` in the construct method of the controller.
class HomeController extends Controller
{
    public function __construct()
    {
        $this->user = Auth::user();
    }
    public function index(Request $request){
        print_r($this->user);
  • Get logged in user details using __construct method in controller Laravel 9

    You can get the logged in user details using the construct method in Laravel. You have to call Auth::user() method after auth middleware which checks if the user is authenticated or not in the construct method and after that you can get the details of the logged in user.

    app\Http\Controllers\HomeController.php

    use Auth;
    
    
    class HomeController extends Controller
    {
    
        public function __construct()
        {
            $this->middleware('auth');
            $this->middleware(function ($request, $next) {
                $this->user = Auth::user();
    
                return $next($request);
            });
        }
    
        public function index(){
    
            print_r($this->user);
    

    Output

    Array ( [id] => 15 [name] => samar [email] => [email protected] [email_verified_at] => [username] => samar [created_at] => 2022-03-08T08:26:50.000000Z [updated_at] => 2022-03-08T08:26:50.000000Z )

Back to code snippet queries related laravel