Save or update pivot table data with additional column in Laravel
Save or update pivot table data with additional column in Laravel
Hello everyone, in this post we will examine how to solve the "Save or update pivot table data with additional column in Laravel" programming puzzle.
Sometimes we have to save or update pivot table data with additional column in Laravel because of unique combination of values in table. Here we have code snippet which helps you to create a record in pivot table if record is not exists in table or update records if exists in it.-
Create if not exists and update record if exists in pivot table with extra column using attach and updateExistingPivot method in Laravel
--PATH routes\web.phpRoute::get('/save-or-update-pivot-table-record', function(){ $user = App\Models\User::find(1); $project = App\Models\Project::find(1); if (!$user->projects->contains($project->id)) { $user->projects()->attach($project->id, ['is_manager'=> 1]) ; }else{ $user->projects()->updateExistingPivot($project->id, ['is_manager'=> 0]); } });
This code snippet will help you to create a record in pivot table with extra column if record is not already exists in it and update record if exists in pivot table.
Projects method with belongsToMany relation
app\Models\User.php
public function projects(){ return $this->belongsToMany('App\Models\Project') ->withPivot('is_manager') ->withTimestamps(); }
-
Create if not exists and update record if exists in pivot table with additional column using sync method
--PATH routes\web.phpRoute::get('/save-or-update-pivot-table-record', function(){ $user = App\Models\User::find(1); $project = App\Models\Project::find(1); $user->projects()->sync([$project->id => ['is_manager'=> 1]], false); });
This code snippet will help you to create a new record if the record is not already exist in pivot table else it will update the existing record from table.
-
Create project table with model and migration
// Create project model with migration php artisan make:model Project --migration // Add columns to project migration file under - database\migrations\<2021_04_21_125826>_create_projects_table.php Schema::create('projects', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); // Run migrate command to create table structure php artisan migrate
First you have to run artisan command with php artisan make:model Project --migration. This command will create a model and migration for your table structure. After that you can add columns to the migration file and run the php artisan migrate command.
-
Create pivot table in laravel with multiple columns
--PATH database\migrations\<yourmigrationfile>.php//Migration command to create migration file php artisan make:migration create_project_user_table --create=project_user //Migration file code under - database\migrations\<yourmigrationfile>.php public function up(){ Schema::create('project_user', function (Blueprint $table) { $table->foreignId('project_id')->constrained(); $table->foreignId('user_id')->constrained(); $table->boolean('is_manager')->default(false); $table->timestamps(); }); }
You can add multiple columns in the laravel pivot table using migration. This code snippet adds is_manager columns in the pivot table with default value false and adds created_at and updated_at fields using timestamps method.
Related Queries
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
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.
Random Code Snippet Queries: Laravel
- How to update record after save method in Laravel
- Post table seeder laravel 10
- How to get tomorrow and yesterday date in laravel
- Get only 10 records from table in laravel
- Syntax error or access violation: 1072 Key column 'role_id' doesn't exist in table (SQL: alter table `users` add constraint `users_role_id_foreign` foreign key (`role_id`) references `roles` (`id`))
- Submit form without CSRF token in Laravel
- Get the post details if it has at least one comment in comments table
- Add class to body in laravel view
- How to create new user without form submission in laravel
- Attempt to read property "avatar" on null in Laravel
- Php artisan make model, factory, migration and controller in single command
- How to change default timestamp fields name in Laravel
- File_put_contents(/var/www/html/w3code/storage/framework/sessions/CXwN3EXKxERD6jgy3rADcaAAbAx8FRKih2JK7UO9): Failed to open stream: Permission denied
- Route [password.request] not defined
- Post model with title and body in laravel 8
- How to send ID to another page in Laravel
- Create model with migration and seeder
- Display data in table using foreach in Laravel
- How to show data by ID in laravel?
- How to add a key value pair to existing array in laravel
- How to generate .env file for laravel?
- How to create pivot table in laravel using migration
- How to increment column value of table in Laravel
- How to authenticate admin users in Laravel ?
- Laravel insert query not working