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


first time try laravel eloquent relatioinstip

i know it's simple getting error don't know what's wrong

i have 2 tables in data base, news , 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 $new) <tr>    <td> {{$new->id}} </td>    <td> {{ $new->header}}</td>    <td> {{ $new->details }}</td>    </td> {{$new->news->image}}</td> </tr> 

when run it's error :

trying property of non-object (view: /var/www/html/clinics/app/views/news/index.blade.php)

any ideas on causing error?

there couple things change:

  1. in news model, change relationship "image" "images" since it's 1 many relationship. keeps code clean.

  2. your foreach loop in view should loop through news models, remember each news model has multiple images, should have loop inside existing loop display images, i.e. foreach ($new->images $image)

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

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -