1// in User model:
2<?php
3
4namespace App;
5
6use Illuminate\Database\Eloquent\Model;
7
8class User extends Model
9{
10 /**
11 * The roles that belong to the user.
12 */
13 public function roles()
14 {
15 return $this->belongsToMany('App\Role');
16 }
17}
18
19// in Role model:
20<?php
21
22namespace App;
23
24use Illuminate\Database\Eloquent\Model;
25
26class Role extends Model
27{
28 /**
29 * The users that belong to the role.
30 */
31 public function users()
32 {
33 return $this->belongsToMany('App\User')->using('App\UserRole');
34 }
35}
1For example, a blog post may have an infinite number of comments. And a single
2comment belongs to only a single post
3
4class Post extends Model
5{
6 public function comments()
7 {
8 return $this->hasMany('App\Models\Comment');
9 }
10}
11
12class Comment extends Model
13{
14 public function post()
15 {
16 return $this->belongsTo('App\Models\Post');
17 }
18}
1// Detach a single role from the user...
2$user->roles()->detach($roleId);
3
4// Detach all roles from the user...
5$user->roles()->detach();
1$user->roles()->attach($roleIds);
2$user->roles()->detach($roleIds);
3$user->roles()->sync($roleIds);
4$user->roles()->toggle($roleIds);
1class Post extends Model
2{
3 // 1 Post has many comments
4 public function comments()
5 {
6 return $this->hasMany(Comment::class);
7 }
8}
1<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserRole extends Model{ }