Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: How to add Auth::user()->id through the constructor ?

I can get the ID of the authenticated user like this:

Auth::user()->id = $id;

Great it works, ... but I have a load of methods which need it and I want a cleaner way of adding it to the class as a whole,so I can just reference the $id in each method. I was thinking of putting it into the constructor, but as Auth::user is a static, I am making a mess of things and don't know how to do it.

Many thanks for your help !

like image 239
Vince Avatar asked Jun 22 '15 21:06

Vince


2 Answers

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 UserController extends Controller {

    protected $userId;

    public function __construct() {

        $this->middleware(function (Request $request, $next) {
            if (!\Auth::check()) {
                return redirect('/login');
            }
            $this->userId = \Auth::id(); // you can access user id here
     
            return $next($request);
        });
    }
}
like image 51
Ali Sherafat Avatar answered Oct 12 '22 08:10

Ali Sherafat


Instead of using the Facade you can inject the contract for the authentication class and then set the user ID on your controller. Like @rotvulpix showed you could put this on your base controller so that all child controllers have access to the user ID too.

<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Auth\Guard;

class FooController extends Controller
{
    /**
     * The authenticated user ID.
     *
     * @var int
     */
    protected $userId;

    /**
     * Construct the controller.
     *
     * @param  \Illuminate\Contracts\Auth\Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->userId = $auth->id();
    }
}

The guard has an id() method which returns void if no user is logged in, which is a little easier than having to go through user()->id.

like image 25
Dwight Avatar answered Oct 12 '22 07:10

Dwight