Skip to content

Instantly share code, notes, and snippets.

@pmkay
Created October 4, 2018 16:55
Show Gist options
  • Save pmkay/5bd74b4c4e540414c8d64efcfc9a8f18 to your computer and use it in GitHub Desktop.
Save pmkay/5bd74b4c4e540414c8d64efcfc9a8f18 to your computer and use it in GitHub Desktop.
Creating a Pivot Table in Laravel Example
<?php
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->primary(['post_id', 'tag_id']);
$table->unsignedInteger('post_id');
$table->unsignedInteger('tag_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
}
}
class Post
{
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps;
}
}
Class Tag
{
public function posts()
{
return $this->belongsToMany(Post::class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment