Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Hi ItsRD , assuming that you have owner as a boolean in your migration here is what you have to do.

Project Model

 public function users()
{
    return $this->belongsToMany('App\User')->withPivot('owner');
}

withPivot lets you define others columns apart from the ids of the relationship. Documentation in the section: Retrieving Intermediate Table Columns

User Model

 public function projects()
{
    return $this->belongsToMany('App\Project')->withPivot('owner');
}

The same here.

Attaching Example

Route::get('attach',function (){

    $user = App\User::find(1);
    $user->projects()->attach(1,['owner'=> true]);
    $user->projects()->attach(3,['owner'=> false]);

    $user = App\User::find(2);
    $user->projects()->attach(3,['owner'=> true]);
});

I just create a database seeder with three projects and two users and use the route for attaching. Do it as you like it.

Project Item Blade

<h1>Name: {{ $project->name }}</h1>  
<p>Users: </p>
@foreach($project->users as $user)
<li>{{$user->name}} Owner: {{ $user->pivot->owner }}</li>
@endforeach

Output

Simple blade output

More info about pivot tables

Out of topic: Where are you from?

Last updated 9 years ago.
0

Awesome, it worked! Thank you so much!

I'm from the Netherlands and yea... I know my english is terrible.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

ItsRD itsrd Joined 11 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.