Peter Matisko
Peter Matisko

Reputation: 2253

Laravel 5.4 Sessions and Auth::user() not available in controller's constructor

I would like to use a User class throught the application. So, I would like to create CustomUser and then inject it into controllers that need it (it would be most of them).

Now, I create an empty instance in serviceprovider. Next, I want to fill it with data that are already saved in Auth::user(). After long time I have not found where to do it.

Auth::user() is empty in middlewares, but is filled with the user data in controllers. I am missing the step where Laravel queries the database and fills Auth:user() with data. I want to avoid making the same query again.

Thanks for any help!

Upvotes: 3

Views: 4177

Answers (3)

Rajat Masih
Rajat Masih

Reputation: 583

In Laravel 5.6 i used this

$this->middleware(function ($request, $next) {
        $id = Auth::user()->id;
        $res = $this->validateAnyFunction($id);
        if(!$res){
        //to redirect to any other route
            return $next(redirect()->route("any")->with("failed","Invalid")->send());
        }
        //this is used to proccess futher funcitons of controller
        return $next($request);
    });

Upvotes: 0

Andrii Lutskevych
Andrii Lutskevych

Reputation: 1379

You can use base controller with __get() method. For example:

class Controller
{
    public function __get(string $name)
    {
        if($name === 'user'){
            return Auth::user();
        }

        return null;
    }
}

And in the child controllers can call $this->user

Upvotes: 4

Ohgodwhy
Ohgodwhy

Reputation: 50767

Since Laravel 5.3, you do not have access to sessions in controller constructors. This is because the middleware has not been run yet. I know it's difficult to locate, but in the migration documentation from 5.2 > 5.3 (you're probably on 5.4), it shows that the proper way to resolve data from sessions (which auth() is just a wrapper around a session() call to get the user), is to use the following method:

class MyController extends Controller {
    protected $user;

    public function __construct() {
        $this->middleware(function ($request, $next) {
           $this->user= auth()->user();

           return $next($request);
        });
    }
}

Then $this->user will reference the auth user to any methods inside of this controller.

Hopefully his helps.

Upvotes: 3

Related Questions