Eloquent Many to Many Relationship CRUD

We will need a new model and migrations for role and role_user

php artisan make:model Role -m
php artisan make:migration create_user_role_table --create=role_user
Here we are creating a pivot table which follows the some rules: alphabetical order of the two table names in singular case

In our migrations add this to role_user:

            $table->integer('user_id')->unsigned()->nullable()->index();
            $table->integer('role_id')->unsigned()->nullable()->index();

And this to role:

            $table->string('name');

Now you can migrate it:

php artisan migrate

Update Models with fillable content for Role and a roles method for User.

Role:

    protected $fillable = [
        'name',
    ];

User:

    public function roles(){
        return $this->belongsToMany('App\Models\Role');
    }

Different CRUD statements to add to routes:

Route::get('/create', function () {
    $user = User::findOrFail(1);
    $role = new Role(['name'=>'Administrator']);
    $user->roles()->save($role);
});

Route::get('/read', function () {
    $user = User::findOrFail(1);
    foreach($user->roles as $role){
        echo $role->name;
    }
});

Route::get('/update', function () {
    $user = User::findOrFail(1);
    if($user->has('roles')){
        foreach($user->roles as $role){
            if($role->name=="Administrator"){
                $role->name="subscriber";
                $role->save();
            }
        }
    }
});

Route::get('/delete', function () {
    $user = User::findOrFail(1);
    foreach($user->roles as $role){
        $role->whereId(3)->delete();
    }
});

Route::get('/attach', function () {
    $user = User::findOrFail(1);
    $user->roles()->attach(4);
});

Route::get('/detach', function () {
    $user = User::findOrFail(1);
    $user->roles()->detach(4);
});

Route::get('/sync', function () {
    $user = User::findOrFail(1);
    $user->roles()->sync([4,5,6]);
});
Attach won't check the database to see if it's already been attached.. so with this method you'll need to check your database.

Sync is a bit better because it won't add duplicates. If you don't add previous roles in the database to the sync method, then it will delete those old roles.

Leave a Reply

Your email address will not be published.