A
A
adrenalinruslan2020-03-02 20:24:14
Laravel
adrenalinruslan, 2020-03-02 20:24:14

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');
    }
}


How do I call:
dump(
      User::find(1)->moderator()
    );


And an error comes out:
Call to a member function moderator() on null

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2020-03-03
@neuotq

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 question

Ask a Question

731 491 924 answers to any question