Laravel create multiple records in Pivot table

Created 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.

Related Queries

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.