Search code examples
authenticationlaravelconstructor

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 !


Solution

  • You can use Auth::user() in the whole application. It doesn't matter where you are. But, in response to your question, you can use the 'Controller' class present in your controllers folder. Add a constructor there and make the reference to the user ID.

    <?php namespace App\Http\Controllers;
    
    use Illuminate\Foundation\Bus\DispatchesCommands;
    use Illuminate\Routing\Controller as BaseController;
    use Illuminate\Foundation\Validation\ValidatesRequests;
    
    /* Don't forget to add the reference to Auth */
    use Auth;
    
    abstract class Controller extends BaseController {
    
        use DispatchesCommands, ValidatesRequests;
    
        function __construct() {
            $this->userID = Auth::user()?Auth::user()->id:null;
        }
    }
    

    Then, in any method of any controller you can use the $this->userID variable.