Search code examples
authenticationlaravel-5laravel-5.3illuminate-container

Get authentication data inside of Constructor issue in Laravel5.3.19


I have upgrade Laravel from 4.2 to laravel5.3 but I can't access Authentication data inside of Constructor of Controller

I have as below Middleware but it never work for me

use App\Http\Controllers\BaseController;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Redirect;
use Auth;
use App\User;


class DashboardController extends BaseController
{

    public $user;

    public function __construct(Guard $guard, User $user)
    {
        $this->middleware(function ($request, $next) {
            $this->user = Auth::user();
            return $next($request);
        });
        //$this->userID = Auth::user()?Auth::user()->id:null;

        dd($user);// Result attributes: []
        dd($guard);
        dd($this->user);

    }

}

The result after DD()

dd($guard); This is the result of $guard

DD($this->user);

NULL

It will return Null when I dd user property.


Solution

  • This is to be expected. The reason you have to assign the user inside the middleware closure is because the session middleware hasn't run yet. So, the closure you have above won't actually be called until later in the execution process.

    If you move the dd($this->user) to inside the middleware closure or in to your one of you route methods in that controller it should be working absolutely fine.

    Also, just FYI, in your middleware closure you can get the user instance from the request i.e. $request->user() will give you the authenticated user.

    Hope this help!