J
J
javanub2016-12-06 13:04:41
Laravel
javanub, 2016-12-06 13:04:41

Links not working properly?

I'm trying to display related tables, news and countries

$news = NewsModel::with('country')->paginate(1);
return view('welcome', ['news' => $news]);

I get a normally connected json
8edebf460d3d48a9929345287eb1c006.png
In the news model, just in case, like this:
public function country()
{
     return $this->belongsTo(CountryModel::class, 'country', 'id');
}

But when I do this, it doesn't work: Trying to get property of non-object
@foreach($news as $item)
    {{ $item->country->country }}
@endforeach

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
javanub, 2016-12-06
@javanub

holfza gave the right advice to rename the method in the model different from the name of the cell in the database.

A
Andrzej Wielski, 2016-12-06
@wielski

If one $item element does not have a country, then of course it will fail.
Check before output:
{{ $item->country ? $item->country->country : ''}}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question