How to add unique records in pivot columns of Laravel pivot table

You can add unique records in pivot columns of Laravel pivot table using several ways. You can first check the value of pivot column is already exists or not and you can insert value if value is not already exists in it. You can also use composite key method which avoids duplicate value in pivot table

Answers 1
  • Insert unique value combination in pivot columns of Laravel pivot table

    //routes\web.php
    Route::get('/insert-in-pivot-table', function(){
        $user = App\Models\User::find(1);
        $project = App\Models\Project::find(1);
    
        if (!$user->projects->contains($project->id)) {
            $user->projects()->save($project);
        }
    });
    
    0

    You can insert records in pivot table after checking the value in pivot column of pivot table is not already exists. You have to create users, projects and project_user pivot tables. You have to also create projects method with belongsToMany relation in User model.

     

    Projects method with belongsToMany relation

    app\Models\User.php

    public function projects(){
        return $this->belongsToMany('App\Models\Project')
                    ->withTimestamps();
    }
  • Back to code snippet queries related laravel

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