How to Utilize Laravel 10 Pivot Tables?

22-Dec-2023

.

Admin

How to Utilize Laravel 10 Pivot Tables?

Hello Dev,

This tutorial will provide an example of how to utilize Laravel 10 pivot tables. we will help you to give examples of how to delete pivot tables in Laravel 10. I explained simply how to store data in a pivot table in Laravel 10. step by step explain how to update the pivot table in Laravel 10. Let's see bellow an example three-way pivot table with eloquent.

In Laravel, a 'pivot' table is a specialized type of database table employed in many-to-many relationships between two other tables. It is commonly used to store the relationships between models, along with any additional attributes or data associated with that relationship.

Let's break down the concept of a pivot table and explore how it's used in Laravel.

Scenario:


Imagine you have two main entities: User and Role. A user can have multiple roles, and a role can belong to multiple users. This is a classic example of a many-to-many relationship.

Database Structure: Representing this many-to-many relationship typically involves the use of three tables.

users: Stores user information.

roles: Stores role information.

role_user (pivot table): Stores the relationships between users and roles, along with any additional data.

Laravel Implementation:

Step 1: Define Models.

Create the User and Role models, and in each model, define the belongsToMany relationship to establish the many-to-many connection.

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Authenticatable

{

use HasApiTokens, HasFactory, Notifiable;

/**

* The attributes that are mass assignable.

*

* @var array<string>

*/

protected $fillable = [

'name',

'email',

'password',

'image',

];

/**

* write code for.

*

* @param \Illuminate\Http\Request

* @return \Illuminate\Http\Response

* @author <>

*/

class User extends Model

{

public function roles()

{

return $this->belongsToMany(Role::class);

}

}

}

app/Models/Role.php

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

use Illuminate\Database\Eloquent\Relations\HasOne;

class User extends Authenticatable

{

use HasApiTokens, HasFactory, Notifiable;

/**

* The attributes that are mass assignable.

*

* @var array<string>

*/

protected $fillable = [

'name',

'email',

'password',

'image',

];

/**

* write code for.

*

* @param \Illuminate\Http\Request

* @return \Illuminate\Http\Response

* @author <>

*/

class Role extends Model

{

public function users()

{

return $this->belongsToMany(User::class);

}

}

}

Step 2: Database Migration.

Generate migration files for the users, roles, and role_user tables. Ensure that the pivot table, role_user, includes additional columns to store any data associated with the relationship.

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class AddPostIdToProductsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('role_user', function (Blueprint $table) {

$table->unsignedBigInteger('user_id');

$table->unsignedBigInteger('role_id');

$table->timestamps();

// Additional columns for pivot data

// $table->string('additional_data');

$table->foreign('user_id')->references('id')->on('users');

$table->foreign('role_id')->references('id')->on('roles');

});

}

}

Step 3: Usage.

Utilize the established relationships to attach or detach roles to and from users.

// Attaching roles to a user

$user = User::find(1);

$role = Role::find(2);

$user->roles()->attach($role->id);

// Detaching roles from a user

$user->roles()->detach($role->id);

// Sync roles for a user (replacing all existing roles)

$user->roles()->sync([1, 3]);

Furthermore, you have the capability to interact with the pivot data and attributes linked to the relationship.

// Accessing pivot data

$pivotData = $user->roles()->where('role_id', $role->id)->first()->pivot;

// Updating pivot data

$user->roles()->updateExistingPivot($role->id, ['additional_data' => 'new_value']);

Pivot tables stand out as a powerful feature in Laravel's Eloquent ORM, providing a flexible and efficient way to manage many-to-many relationships. They find common use in scenarios where there's a need to associate additional data or attributes with the relationship between two models.

I hope it can help you...

#Laravel 10