rockstardev
rockstardev

Reputation: 13527

Laravel: How to see if user is logged in in Base Controller?

I want to be able to change a field called "last_accessed" in the users table on each and every request the user makes.

I have a controller called "ContentController" which extends "Controller". So I figured just adding code in the constructor of "Controller":

public function __construct()
{
  $user = \Auth::user();
  if (Auth::check()) {
    print 'Good';
  }
  else print "Bad";
}

No matter what I do, I can't it to see that I'm authorized.

Can someone please tell me:

  1. Why is AUTH not working in the base controller?
  2. How can I update the last_accessed field upon each view if this controller idea of mine isn't possible?

Upvotes: 0

Views: 121

Answers (1)

Dimitri Mostrey
Dimitri Mostrey

Reputation: 2355

Because that doesn't work in __construct(). There is a workaround. It works but I'm not sure if some other Laravel users will accept my answer. What you should do is create a middleware and work from there. You can use an anonymous function, which in this case, mimics a middleware:

public function __construct(Request $request)
{
    $this->middleware(function ($request, $next) {
        $user = $request->user();
        if ($user) {
            print 'Good';
        }
        else print "Bad";

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

If no user is logged in, $user will be null.

Upvotes: 1

Related Questions