Laravel Many to Many Relationships

Laravel Many to Many Relationships

Programming - Mar 27, 2024

This is an example of how to define and work with many-to-many relationships in Laravel. Let's say we have two models: `User` and `Role`, and we want to establish a many-to-many relationship between them, where a user can have multiple roles and a role can be assigned to multiple users.

First, let's create the `User` and `Role` models using the Laravel Artisan command:

php artisan make:model User -m
php artisan make:model Role -m

This will generate migration files for both models. Let's define the structure of these tables in their respective migration files:

1. For the `users` table:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

2. For the `roles` table:

Schema::create('roles', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

Now, we need a pivot table to establish the many-to-many relationship between `users` and `roles`. Let's create a migration for the pivot table:

php artisan make:migration create_role_user_table

In the generated migration file, define the structure of the pivot table like this:

Schema::create('role_user', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id');
    $table->unsignedBigInteger('role_id');
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});

Now, let's define the relationships in the models. In the `User` model:


namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}


And in the `Role` model:

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}


With these relationships defined, you can now work with the `users` and `roles` tables and their related data using Eloquent ORM methods provided by Laravel. For example:

// Assigning roles to a user
$user = User::find(1);
$user->roles()->attach([1, 2, 3]);

// Getting roles of a user
$roles = $user->roles;
// Getting users with a specific role

$role = Role::find(1);
$users = $role->users;

These are just some basic examples of how to work with many-to-many relationships in Laravel. You can perform various operations like attaching, detaching, syncing, etc., based on your application's requirements.

Previous Next
Copyrights
We respect the property rights of others, and are always careful not to infringe on their rights, so authors and publishing houses have the right to demand that an article or book download link be removed from the site. If you find an article or book of yours and do not agree to the posting of a download link, or you have a suggestion or complaint, write to us through the Contact Us .
Read More