I have 2 tables issues
and magazines
and they have a relationship set up like this:
Magazines model:
public function issues()
{
return $this->hasMany('App\Issue');
}
Issues model:
public function magazine()
{
return $this->belongsTo('App\Magazine');
}
In the magazines table I have a column order
where the order number of the magazine is. I need to display the latest issue of each magazine, ordered by the magazine order.
Now I am displaying latest issue of each magazine ordered by the date of issues.
$issues = Issue::orderBy('date', 'desc')->get()->groupBy('magazine_id');
foreach ($issues->first() as $issue)
{
$images[] = $issue->image;
}
And that works fine. But with the new query:
$magazines = Magazine::with('issues')->orderBy('order')->get();
foreach ($magazines as $magazine)
{
$issues = $magazine->issues()->first();
$images[] = $magazine->issues()->first()->image;
}
I get the error:
Trying to get property of non-object