Created
August 3, 2015 16:14
-
-
Save patrickisgreat/f445478c294fc78346fa to your computer and use it in GitHub Desktop.
Quick and Dirty Laravel Many to Many example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //So you have your pivot table all set up.... So in a "Role," model (ha!) you would set up a many to many relationship like so: | |
| <?php | |
| public function users() | |
| { | |
| return $this->belongsToMany('\App\User'); | |
| } | |
| //and in your User model you would do something like: | |
| public function roles() | |
| { | |
| return $this->belongsToMany('\App\Role'); | |
| } | |
| //and in your controller you would do something like this to get a user with their roles | |
| $this->UserWithRoles = Auth::user()->with('roles')->get(); | |
| //and to update the users roles pivot table you could do something like this | |
| User::roles()->attach($data['role_name']); | |
| //and to remove a User's roles from the pivot table you could do something like this | |
| User::roles()->detach(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment