rinaldy31
rinaldy31

Reputation: 127

Trying to get property of non-object [laravel 5.2]

I'm getting trouble in getting the data from foreign key . already make relation between 2 tables, but still error gave me this "Trying to get property of non-object"

this is my models

public function tourism()
{
    return $this->belongsTo('App\Models\Tourism','tourism_id');
}

this is my controller

 $ratings = Ratings::orderBy('rating','desc')->get();
    $ratings = $ratings->take(6);

and this is my blade

<tbody>
 @if($ratings)
      @foreach($ratings as $data)
            <tr>
                 <td class="center">{{$data->id}}</td>
                 <td class="center">{{$data->tourism_id->nama}}</td>
                 <td class="center">{{$data->rating}}</td>
            </tr>
@endforeach
 @endif
</tbody>

thanks

Upvotes: 1

Views: 844

Answers (3)

Laravel User
Laravel User

Reputation: 1129

in your controller use it like this:

$ratings = Ratings::orderBy('rating','desc')->take(6)->get();

Upvotes: 0

geckob
geckob

Reputation: 8130

Assuming you already have this controller and the model relationship as above:

function ratingsView() {

 $ratings = Ratings::orderBy('rating','desc')->get();
 $ratings = $ratings->take(6);

 return View('rating')->with('ratings',$ratings);

}

In your views,

<tbody>
 @if($ratings)
      @foreach($ratings as $data)
            <tr>
                 <td class="center">{{$data->id}}</td>
                 <td class="center">{{$data->tourism()->first()->nama}}</td>
                 <td class="center">{{$data->rating}}</td>
            </tr>
@endforeach
 @endif
</tbody>

Make sure your rating table have id, rating as well as tourism_id attributes and your tourism table have name attribute as well as of course there is data in both tables.

You definitely need to check the the availability of the data and handle it accordingly. But that is different issue

Upvotes: 0

huuuk
huuuk

Reputation: 4795

Try

<td class="center">{{$data->tourism->nama}}</td>

EDIT

This situation occurs when you trying get nama property. But tourism_id it's just an integer, am I right? First of all,for accessing related model you should use you relationship method(tourism) instead of FK field(tourism_id).
Then you should check are there any related model in tourims() or not. For this purpose i recommend you use ternary operator, so your line should be something like:

<td class="center">{{$data->tourism->first() ? $data->tourism->first()->nama : 'No tourism'}}</td>

Upvotes: 2

Related Questions