Many to Many Relationship

Suppose one user has many roles.
ankur = admin,editor
salman = editor,author
You need to create 3 tables in your Database. users, roles, and role_user. After creating your table, you need to data insert

cd Directory
php artisan tinker
DB::table('users')->insert(['name'=>'Ankur','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('users')->insert(['name'=>'Salman','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'admin','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'editor','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'author','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'1','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'2','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'2','user_id'=>'2','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'3','user_id'=>'2','created_at'=>new DateTime,'updated_at'=>new DateTime])

Now you have to create model

cd Directory
php artisan make:model user
php artisan make:model role

User model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    public function roles()
    {
    	return $this->belongsToMany(Role::class);    
       
        /* If your table name is role_users. So You have to pass your table name as the second parameter */
        //return $this->belongsToMany(Role::class,'role_users');    
    }   
}

Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);

        /* If your table name is role_users. So You have to pass your table name as the second parameter */
        //return $this->belongsToMany(User::class,'role_users'); 
    }
}

Retrieve the related record:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class HomeController extends Controller
{
    public function index(){
    	$roles = user::find(2)->roles;    	
    	//$roles = user::find(2)->roles()->orderBy('role')->get();    	
    	return view('welcome',compact('roles'));
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s