Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iroberto83's avatar

Create pivot table from artisan

Hi! I've read about many-to-many relationship on laravel from https://laravel.com/docs/5.6/eloquent-relationships#many-to-many , but I don't know how create intermediate table. From artisan, on make:model, I've found the -p attribute :

-p, --pivot Indicates if the generated model should be a custom intermediate table model.

But how i specify the models implied?

0 likes
8 replies
tykus's avatar

A typical pivot table does not require a Model; you only need a migration, e.g.

php artisan make:migration create_role_user_table

By convention, Laravel expects the related model names in alphabetical order (you can break with this convention if your prefer). A typical pivot table would just have the foreign keys:

public function up()
{
        Schema::create('role_user', function (Blueprint $table) {
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('role_id');
        });
}
6 likes
yazeed's avatar

That's not entirely accurate, it should have the reference to the original tables as well.

public function up()
    {
        Schema::create('account_tag', function (Blueprint $table) {
            $table->integer('account_id')->unsigned()->index();
            $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');

            $table->integer('tag_id')->unsigned()->index();
            $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');

            $table->timestamps();
        });
    }
6 likes
honayme's avatar

And in fact you can create a pivot table generated by artisan by informing the two involved models, like this :

php artisan make:migration:pivot user role

7 likes
seabass's avatar

Is this still working in Laravel 8? I get There are no commands in the "make:migration" namespace

MohammedAlMahmood's avatar

actually , you can create your model and linked it your pivot table by " using " instruction

class Subject extends Model { public function users() { return $this->belongsToMany('App\User') ->using('App\UserSubject'); } }

Please or to participate in this conversation.