Skip to content

Instantly share code, notes, and snippets.

@patrickisgreat
Created August 3, 2015 16:14
Show Gist options
  • Select an option

  • Save patrickisgreat/f445478c294fc78346fa to your computer and use it in GitHub Desktop.

Select an option

Save patrickisgreat/f445478c294fc78346fa to your computer and use it in GitHub Desktop.
Quick and Dirty Laravel Many to Many example
//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