Search code examples
laraveleloquentrelationshipbelongs-to

How to get all records(related and non related) of Laravel belongsTo relationship?


How can I get all the records from the relationship? I mean not only the related records, but also the rest.

Let's say I have a post which belongs to some category. If I want to change the category of this post I need a list of all available categories. Can I get this list from the relationship?

The Post model:

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

The Category model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

In the PostsController I tried:

$postModel->category->find('all'); // Returns null
$postModel->category->all(); // Returns only the related categories

I know I can simply use the Category model in the PostsController, but I prefer to do it using the relationship.


Solution

  • If you feel you must use the relationship to get to the other model you could try:

    $categories = $post->category()->getRelated()->get();