1class Post extends Model
2{
3 // 1 Post has many comments
4 public function comments()
5 {
6 return $this->hasMany(Comment::class);
7 }
8}
1use App\Models\User;
2
3$user = User::find(1);
4
5$user->roles()->attach($roleId);
1/*
2users
3 id - integer
4 name - string
5
6roles
7 id - integer
8 name - string
9
10role_user
11 user_id - integer
12 role_id - integer
13*/
14
15class User extends Model
16{
17 /**
18 * The roles that belong to the user.
19 */
20 public function roles()
21 {
22 /*To determine the table name of the relationship's intermediate
23 table, Eloquent will join the two related model names in
24 alphabetical order. However, you are free to override this
25 convention. You may do so by passing a second argument to the
26 belongsToMany method*/
27 return $this->belongsToMany(Role::class,'role_user');
28 }
29}
30//Defining The Inverse Of The Relationship
31
32class Role extends Model
33{
34 /**
35 * The users that belong to the role.
36 */
37 public function users()
38 {
39 return $this->belongsToMany(User::class);
40 }
41}