Let's talk about a belongs-to-many, also called many-to-many relationships, but on a deeper level. What are other options besides the foreign keys columns in the pivot table?
This is a typical pivot table between a project and a user. A project may belong to many users.
Schema::create('project_user', function (Blueprint $table) { $table->foreignId('project_id')->constrained(); $table->foreignId('user_id')->constrained();});
To show users for each project, you typically get the projects with user relations and do a foreach loop.
use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Project extends Model{ public function users(): BelongsToMany { return $this->belongsToMany(User::class); }}
$projects = Project::with('users')->get(); foreach ($projects as $project) { print $project->id . ': ' . $project->title . ' ('; foreach ($project->users as $user) { print $user->email .'; '; } print ')<hr />';}
This is a typical default simple belongs-to-many relation.
Adding Timestamps to Pivot
What can we add to the pivot? For example, you want to know when that record was added. By default, pivot tables are without timestamps. To enable timestamps, we must first add columns to the migration.
Schema::create('project_user', function (Blueprint $table) { $table->foreignId('project_id')->constrained(); $table->foreignId('user_id')->constrained(); $table->timestamps(); });
But that wouldn't be enough. Timestamps, by default, wouldn't be set in a pivot table. To enable setting timestamps in the relationship belongs-to-many, you need to...