Answer the question
In order to leave comments, you need to log in
I'm getting an error, I can't figure out what's wrong?
File: User.php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function moderator()
{
return $this->hasOne('App\Moderator');
}
}
dump(
User::find(1)->moderator()
);
Call to a member function moderator() on null
Answer the question
In order to leave comments, you need to log in
If null is returned, which means there is no user with id 1, then the further chain will not work, since the "magic" will not work due to the lack of an object of the User class.
It’s better to find the user in advance and save them to a variable (this will also allow you not to make additional requests to the database if you use the entity again).
And then you can already use existence checks before the call method, for example:User::find(1)
$user = User::find(1);
$moderator = isset($user) ? $user->moderator : null;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question