Muhammed
Muhammed

Reputation: 586

Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object

First time to try laravel eloquent relatioinstip

I know it's really simple but I am getting this error don't know what's wrong with it

I have 2 tables in data base, news and news_image

in database

Tables:

news  
id | header | details 

news_image
id | image | news_id 

And have 2 models News , newsImage

newsImage model :

 class newsImage extends Eloquant {

    protected $table = 'news_image';
    public function news()
    {
        return $this->belongsTo('News');
    }    
}

News model

class News extends Eloquent 
{

    protected $table = 'news';

    public $timestamps = false;


    public function image()
    {
        return $this->hasMany('newsImage');
    }


}

The view:

foreach($news as $new)
<tr>
   <td> {{$new->id}} </td>
   <td> {{ $new->header}}</td>
   <td> {{ $new->details }}</td>
   </td> {{$new->news->image}}</td>
</tr>

when I run this it's get error :

Trying to get property of non-object (View: /var/www/html/clinics/app/views/news/index.blade.php)

Any ideas on what could be causing this error?

Upvotes: 4

Views: 8533

Answers (2)

wunch
wunch

Reputation: 1092

First, assuming what you are passing to your view is an array or Collection of News objects, you should probably be using $new->image to access the News Item relation. By defining the function image() in your News model, you can access the relation with either the ->image or ->image() calls. In either case, what you need to call is probably

$new->image->first()->image

To break that down:

  • ->image gets the Collection of NewsImage relations
  • ->first() gets the first item in the Collection
  • ->image (the secone one) gets the image field from that NewsImage

If the Collection has more than one item, you can instead loop over it to get all of the images as shown in the other answer.

Upvotes: 3

JasonJensenDev
JasonJensenDev

Reputation: 2407

There are a couple things I would change:

  1. In your News model, change the relationship from "image" to "images" since it's a one to many relationship. It just keeps your code clean.

  2. Your foreach loop in your view should loop through all the news models, but remember that each news model has multiple images, so you should have another loop inside your existing loop to display the images, i.e. foreach ($new->images as $image)

    @foreach ($news as $new)
        <tr>
            <td> {{$new->id}} </td>
            <td> {{ $new->header}}</td>
            <td> {{ $new->details }}</td>
            <td>
                @foreach ($new->images as $image)
                    {{ $image->image }}
                @endforeach
            </td>
        </tr>
    @endforeach
    

Upvotes: 2

Related Questions