Home > OS >  Laravel/Eloquent belongsToMany - Property [people] does not exist on the Eloquent builder instance
Laravel/Eloquent belongsToMany - Property [people] does not exist on the Eloquent builder instance

Time:12-11

I want to get people who applied job posts for employer therefore I have manyToMany relation .

Tables..

applies   ->  | users_id(employee) | posts_id |
posts     ->  | id                 | user_id(employer)  | (other posts cols ... )
user_info ->  | id                 | (name col  etc... for employee)

Post model

public function people()
{
   return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}

Controller

public function index()
{
    $user_id = Auth::id();
    $myPosts = Post::where('user_id',$user_id)->get();
    $employees = Post::where('user_id' , $user_id)->people; // this line

    dd($employees);
}

It works well if I $employees = Post::find(//anyNumber//)->people; but it have to be dynamic for each employer id .

I tried this $employees = Post::where('user_id' , $user_id)->people; but gives error

Property [people] does not exist on the Eloquent builder instance.

CodePudding user response:

find() returns a single model. Post::where('user_id' , $user_id)->people is still an Eloquent Builder instance. You have not finished the query and gotten a model. Using a method to get a model (first(), find(), etc.) should fix the problem. Like this:

employees = Post::where('user_id' , $user_id)->first()->people;

CodePudding user response:

I think what you want to do is something like this:

public function index()
{
    $posts = Auth::user()->posts()->with('people')->get();

    return view("index")->with(["posts" => $posts]);
}

This will give you all the authenticated user's posts and eager load the people relationship, so in your Blade template you can loop through each post and have access to the people associated with each post:

<ul>
@foreach ($posts as $post)
    <li>{{ $post->name }}</li>
    <li>
        <ul>
    @foreach ($post->people as $person)
            <li>{{ $person->name }}</li>
    @endforeach
        </ul>
    </li>
@endforeach
</ul>
  • Related