How to insert value to additional columns in pivot table in laravel

Sometimes we need to create additional columns in the pivot table to insert additional values in table. Pivot table is an intermediate table between two tables which is used to insert records that belong to each other. Like, users can have multiple projects and a project can be assigned to multiple users with additional columns that checks which users are the manager of the project. This is one of the real life examples in which we use a pivot table with additional columns.

Answers 1
  • Insert value to additional columns in pivot table

    // app\Http\Controllers\<YourController>.php
    // Use Before class definition in your controller
    Use App\Models\User;
    //Use Inside controller&rsquo;s method
    $user = User::findOrFail(1);
    $projectIds = array('1', '2');
    $user->projects()->attach($projectIds, ['is_manager'=>1]);
    //Create projects() method with belongsToMany Relationship in - App\Models\User.php
    public function projects(){
        return $this->belongsToMany('App\Models\Project')

    This code snippet is used to insert a value to additional columns in the pivot table. Here we use belongs to many relationships in the User model to get the projects table records with pivot table data using withPivot method. 


    To create project model and table structure of project table visit here - Create project table with model and migration .
    If you want to get code snippets to create pivot table for projects and users tables you can visit here -  create pivot table  .
  • Back to code snippet queries related laravel

Related queries helps you to understand and may also used for implementation of current code snippet