简体   繁体   中英

Relationship method must return an object in laravel eloquent

I am trying to find a row with condition and that is...

A user has many profile pictures but there is one picture that is is_main

So this is what I wrote

public function profile_picture()
{
    return $this->hasMany('App\User_profile_picture');
}

public function active_picture()
{
    return $this->profile_picture()->find($this->is_main);
}

Now when I access it through

$picture = Auth::user()->active_picture;

It says

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

What is that I have to do to make it work?

Your code should be

public function profile_picture()
{
    return $this->hasMany('App\User_profile_picture');
}

You are missing the return statement

I think you can try this:

public function profile_picture()
{
    return $this->hasMany('App\User_profile_picture');
}

public function active_picture()
{
    return $this->profile_picture()->find($this->is_main);
}

Hope this work for you !!!

You must use class :

public function profile_picture()
{
   return $this->hasMany(App\User_profile_picture::class);
}

If you want to use a Model method as a property, it has to return a relationship. Otherwise you need to call it as a method with the () operator. Like explained here .

So the solution to your question would be:

$picture = Auth::user()->active_picture();

edit: TIL you can also set a custom eloquent accessor:

public function getActivePictureAttribute()
{
    return $this->profile_picture()->find($this->is_main);
}

$picture = Auth::user()->active_picture;

Yeah, you have to write the get...Attribute in camelCase, and can then use the attribute in snake_case/kebab-case or camelCase. (See the eloquent $snakeAttributes boolean variable.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM