1

When I use php artisan api:routes I receive the following error:

Trying to get property 'hostname_id' of non-object

I have the following code where is this error :

protected $user;
protected $hostname_id;

public function __construct() {
    $this->user = JWTAuth::user();
    $this->hostname_id = $this->user->hostname_id;
   }

I read something that JWTAuth::user() return null and because of that i can not het hostname_id. Maybe is another way to receive loggedIn user data from JWT token?

Mindru Ion
  • 373
  • 5
  • 19
  • Hmm, you error doesn't match your code; it says "[...] property **hostname**", but you're trying to access `hostname_id`. Is that a typo or is this occurring somewhere else? – Tim Lewis Sep 16 '19 at 14:45
  • Sorry, I have two controllers and in another is the same code but with `$this->user->hostname` – Mindru Ion Sep 16 '19 at 14:48
  • I solved it, thanks – Mindru Ion Sep 16 '19 at 14:48
  • No problem! The solution is likely the same `$this->user` is `null`, so you can't access a property, `->example`, so either check for `null` before trying to access, or a fallback. Cheers! – Tim Lewis Sep 16 '19 at 14:55

1 Answers1

1

Error happen because when you are run php artisan api:route it is call all controller __constract() function You can use this code

protected $user;
protected $hostname_id;

public function __construct() {
    $this->user = JWTAuth::user();
    $this->hostname_id = $this->user->hostname_id ?? null;
}
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55