Laravel create multiple records in Pivot table

Updated at 27-Oct-2021, By samar

Laravel create multiple records in Pivot table

We will use programming in this lesson to attempt to solve the "Laravel create multiple records in Pivot table".

You can create multiple records in pivot table in Laravel. You have to call attach method on relationship method with array of ids which create multiple records with additional column.
  • Create multiple records in pivot table with additional column using attach method

    --PATH routes\web.php
    Route::get('/create-multiple-pivot-record', function(){
        $user = App\Models\User::findOrFail(1);
        $user->projects()->attach([
            1 => ['is_manager' => false],
            2 => ['is_manager' => true],
        ]);
    });
    

    This code snippet will create multiple records in pivot table in laravel. It will create two records in pivot table with different value in additional column of pivot table. You can pass dynamic value to additional column (is_manager) as well as project id instead of 1 and 2.

  • Create multiple records in pivot table with attach method

    --PATH routes\web.php
    Route::get('/create-multiple-pivot-record', function(){
        $user = App\Models\User::findOrFail(1);
        $user->projects()->attach([1,2]);
    });
    

    This code snippet is used to create multiple records in pivot table in Laravel.

Back to code snippet queries related laravel