Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel class property not returning in response

Tags:

php

laravel

I'm creating an API for a blog using Laravel and in my UserController, for some routes, I get the currently authenticated user as seen below:

public function getUser() {
$user = auth()->user();
return response()->json($user, 200);
}

This returns a json object of the user. I get the user in other functions in the same way. I wanted to move this line into a wider scope so I could access it in all functions so I placed it in the constructor:

    class UserController extends Controller {
        protected $user;
        public function __construct() {
          $this->user = auth()->user();
        }
      }

I refactored getUser to look like this;

public function getUser() {
    return response()->json($this->user, 200);
    }

Now it just returns an empty object and the 200 status code. Why does making it a class property no longer return the object?

like image 545
Yoofi Brown-Pobee Avatar asked Oct 13 '20 22:10

Yoofi Brown-Pobee


Video Answer


1 Answers

The session middleware has not ran yet; the Controller is instantiated before the Request goes through the middleware stack, so you won't have access to session based authentication at that point (so auth()->user() would be null). You can use a Controller middleware to do this though:

class UserController extends Controller
{
    protected $user;

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

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

This middleware will run after the other middleware in the stack so you will have access to the session at that point.

like image 184
lagbox Avatar answered Oct 30 '22 09:10

lagbox