PHP
Customizing Pivot Models for Many-to-Many Eloquent Relationships
Extend Eloquent's many-to-many relationships by defining a custom intermediate model, allowing you to add methods and accessors to your pivot table data.
<?php
// app/Models/RoleUser.php - Your custom pivot model
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleUser extends Pivot
{
protected $table = 'role_user'; // Explicitly define pivot table name
public function createdAtForHumans()
{
return $this->created_at->diffForHumans();
}
}
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class)
->using(RoleUser::class) // Specify the custom pivot model
->withPivot('created_at'); // Ensure pivot columns are available
}
}
// app/Models/Role.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class)
->using(RoleUser::class)
->withPivot('created_at');
}
}
// Usage example:
// $user = User::find(1);
// foreach ($user->roles as $role) {
// echo $role->name . ' assigned ' . $role->pivot->createdAtForHumans() . "
";
// }
How it works: For many-to-many relationships that require additional attributes or behavior on the intermediate (pivot) table, you can define a custom pivot model. This model should extend `Illuminate\Database\Eloquent\Relations\Pivot`. You then instruct your `belongsToMany` relationship to `->using()` this custom model. This enables you to define methods, accessors, or even relationships directly on the pivot data, making your intermediate table more functional.