Sven van den Boogaart
Sven van den Boogaart

Reputation: 12325

laravel 5 custom method in model with query

In my Room object I want to get an Picture with the lowest priority. So to my Room model i've added:

public function picture(){
    Return Picture::where('room_id', $this->id)->orderBy('priority', 'asc')->first();
}

In my controller I call this method like:

public function($id){
  $room = Room::findOrFail($id); 
  $room->picture();
}

But when i try to get it in my view like:

 {{$room->picture}}

I get the following error:

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

When using {{$room}} I dont see any picture object in the room object but the app doesnt crash.

Upvotes: 2

Views: 5297

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40919

If you want to be able to fetch the latest picture like that, you'll need to put relation definition in your pictures() method instead of fetching the object. This way you'll be able to make use of Eloquent's eager loading; fetching the picture with the lowest (in terms of value) priority will also be very easy.

Add the following to your Room class:

//relation definition - one to many
public function pictures() {
  return $this->hasMany(Picture::class);
}

//Eloquent getter
public function getPictureAttribute() {
  return $this->pictures()->orderBy('priority', 'asc')->first();
}

Now, you can easily access the most important picture on a $room object by doing:

$picture = $room->picture;

You can read more about how to set up different types of relations in your models here: http://laravel.com/docs/5.1/eloquent-relationships

Upvotes: 2

Related Questions