Alen
Alen

Reputation: 1291

How to add a condition to a eloquent relation

This is the case I have

$user = User_picture::where('is_main','=',1)->where('user_id','=',Auth::user()->id);

This means a user has many pictures but there is only one picture that has is_main value 1.

I tried this.

public function active_picture()
{
    return $this->hasMany('App\User_picture')->find($this->is_main);
}

This doesn't return anything but an error that says it should be an object. Can anyone help me out with the case?

Upvotes: 0

Views: 576

Answers (2)

jvicab
jvicab

Reputation: 286

You could declare an accessor like:

In User model:

// declare relationship:

public function pictures()
{
    return $this->hasMany(Picture::class);
}

// declare accessor:

public function getMainPictureAttribute()
{
   return $this->pictures()->where('is_main', 1)->first();

}

So you can do this:

auth()->user()->main_picture ...

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

HasMany is meant to return a collection since it is a one to many relationship method.

If you only want to return one result, you should use HasOne with conditions. To define conditions, you use where() not find(). Find() is only used to match the model's primary key.

public function active_picture()
{
    return $this->hasOne('App\User_picture')
           ->where('is_main', 1);
}

Upvotes: 1

Related Questions