Patrick Heppler
Patrick Heppler

Reputation: 181

Laravel relation between 3 models?

I need to define relations between 3 Models in Laravel. I have Users, Documents and Permissions. A User can have many Documents and a Document can be assigned to many Users. That's the easy part, a many-to-many relation.

Now I have a Permission table with two entries, read and write. I can't get my head around it, how to assign read or write permission to a document, based on the User.

For example: User1 can write Document1 and read Document2 User2 can write both User3 can only read both

Upvotes: 0

Views: 81

Answers (1)

milo526
milo526

Reputation: 5083

App\User::find(1)->documents()->save($document, 
                ['read' => true, 'write' => false]);

Also, in your models, add to your relationships:

->withPivot('document_id', 'user_id', 'read', 'write');

This would also be the fields of your table.

And than use

foreach ($user->documents as $document) {
    echo 'Can read: ' . $document->pivot->read;
}

For readability you could add a name to the pivot using:

->withPivot(...)->as('permissions')

And than access the pivot using:

foreach ($user->documents as $document) {
    echo 'Can read: ' . $document->permissions->read;
}

Thanks to bogdan in the comments for the pivot name.

Upvotes: 2

Related Questions