Reputation: 7105
I use Laravel 5.4.36.
When I use Auth::user()->id
on constructor method show me this error
(1/1) ErrorException
Trying to get property of non-object
in UserController.php (line 25)
My controller:
public function __construct()
{
echo Auth::user()->id;
}
But when I use Auth::user()->id
on index method show me 2
public function index()
{
echo Auth::user()->id;
}
result is : 2
And When I test it on AppServiceProvider.php boot method show me this error again
Upvotes: 1
Views: 2153
Reputation: 16817
In Laravel 5.3 and later, the session is not available in controller constructors because the framework invokes these before running the middleware, so auth services have not been initialized.
The documentation suggests the following pattern when we need to use sessions or auth in controller constructors:
class ProjectController extends Controller
{
protected $currentUserId;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->currentUserId = Auth::user()->id;
return $next($request);
});
}
}
This adds a middleware callback to the end of the middleware chain which sets the value of the current user after the session middleware executes. Then we can use $this->currentUserId
from the other controller methods.
Upvotes: 1
Reputation: 3551
The problem is session is still not started in constructor. It will be registered once all middleware will be registered from your app/Http/Kernel.php and what your are trying to fetch will give value only if user session has started.
So in constructer you have to override the middleware function. In your controller file, you can access user session data like this
private $userId;
$this->middleware(function ($request, $next) {
// fetch your session here
$this->userId = Auth::user()->id;
return $next($request);
});
In your index method of that controller
public function index()
{
echo $this->userId;
}
Also make sure user has logged in, otherwise session will not exist for user.
Hope this will help :)
Upvotes: 3
Reputation: 1
This object is not available in the constructor. You can use Midelware or use it in other methods
Upvotes: 0