Wally Kolcz
Wally Kolcz

Reputation: 1664

Laravel relationships issue

Why do realtionships have to be so hard? lol

I am attempting to get the imageName from the Petphoto model which is attached to the Pet Model. In my controller I am adding the Petphoto model using with() but when I go to output it using $pet->photo->imageName, its saying: Undefined property: Illuminate\Database\Eloquent\Collection::$imageName

When I just using $pet->photo, the HTML that is created is [{"imageID":114,"petID":189,"imageName":"P3080066.JPG","dateAdded":"2011-05-27 00:00:00","source":"local","weight":1}]

My Controller:

$pets = Pet::with('photo','breed','secondbreed')->where('status',1)->paginate(50);

My Pet Model:

public function photo(){
    return $this->hasMany('Petphoto', 'petID', 'petID');
}

My Petphoto Model:

public function pet(){
        return $this->belongsTo('Pet');
    }

Any ideas what I am doing wrong? Thanks!

Upvotes: 0

Views: 66

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

Relationships are so darn easy with eloquent, you just made them a bit harder ;)

First I suggest you always name the relations appropriately:

// belongsTo, hasOne singular like:
public function pet()
{
  return $this->belongsTo('Pet');
}

// hasMany, belongsToMany, hasManyThrough plural:
public function photos()
{
  return $this->hasMany('Photo');
}

Then it's obvoius that you can't do this:

$pet->photos->imageName;

for you call $pet->photos which is a Collection.

So to make it work you need to loop through the collection:

// assuming it's a blade template and relation's name is plural like I suggested
@foreach ($pet->photos as $photo)
   <h1>{{ $photo->imageName }}</h1>
@endforeach

..or:

$pet->photos->first()->imageName;

Upvotes: 2

Ray
Ray

Reputation: 3060

Your trying to access a property with your approach - I believe the relationship is a method.

To access the properties of the related model you need to use this method:

`$pet->photo()->imageName`

by adding the brackets you are then using the method (which you've set up in your model) and you should then be able to access the loaded model.

This also works if you want to get a collection of related models $pet->photo()->get()

It's a bit of a gotcha and one I regularly have to get my head round.

Ta

Upvotes: 0

Related Questions