dimanche 24 avril 2016

Nested Eager loading relationships in Laravel

I am creating a forum software using Laravel and I'm trying to access the most recent posts made within a specific topic using latestPost as defined in my model below

    public function latestPost() {
        return $this->hasOne('App\Post')->with('thread')->with('author')->latest();
    }

Here is how the nested relationships are defined in App\Post.php

public function author()
{
    return $this->belongsTo('App\User', 'author_id');
}

public function thread()
{
    return $this->belongsTo('App\Thread', 'thread_id');
}

public function topic() {
    return $this->belongsTo('App\Topic');
}

I have been able to access posts of threads, authors etc no problem, and when I have in my views, it will list the object including relationships successfully. But as soon as I try to display a specific part such as I am getting the following error: Trying to get property of non-object

In this specific view, topics is yet another relationship pulled from Categories like so in the Controller and getting $topics using a @foreach on $categories->topics:

public function index() {
  $categories = Category::orderBy('order', 'asc')->get();

  return view('welcome', compact('categories'));
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire