Afaceri's avatar

Laravel 5.3 Auth::user() available in Controller

Hi,

In Laravel 5.2 I have in my Controller.php the following:

    protected $user;
   protected $signedIn;
   public function __construct() {
        $this->user = $this->signedIn = Auth::user();
    }

  In my routes file I have :

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

.... $this->user is available in all controllers protected by middleware ['auth']

In Laravel 5.3 it does not work ... Why?

0 likes
3 replies
ABDELRHMAN's avatar

laravel docs

In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:

class ProjectController extends Controller
{
    /**
     * All of the current user's projects.
     */
    protected $projects;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->projects = Auth::user()->projects;

            return $next($request);
        });
    }
}
9 likes
Afaceri's avatar

It` works with ....

/*
     *  The authenticated user.protected
      *
      * @var \App\User|null
     */
    protected $user;


    /*
     * Is the user signed In?
     *
     * @var \App\User|null
     */
    protected $signedIn;




    public function __construct() {

        $this->middleware(function ($request, $next) {

            $this->user = $this->signedIn = Auth::user();

            return $next($request);
        });
    }
2 likes
Lord_Sharkca's avatar

This also works, Laravel Documentation


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ProfileController extends Controller
{
    /**
     * Update the user's profile.
     *
     * @param  Request  $request
     * @return Response
     */
    public function update(Request $request)
    {
        // $request->user() returns an instance of the authenticated user...
    }
}
3 likes

Please or to participate in this conversation.