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}
1use Illuminate\Database\Eloquent\Builder;
2
3// Retrieve posts with at least one comment containing words like code%...
4$posts = Post::whereHas('comments', function (Builder $query) {
5 $query->where('content', 'like', 'code%');
6})->get();
7
8// Retrieve posts with at least ten comments containing words like code%...
9$posts = Post::whereHas('comments', function (Builder $query) {
10 $query->where('content', 'like', 'code%');
11}, '>=', 10)->get();
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);
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}