Will you always be passing the full list of ingredients (along with quantities and units) in the Request?
How to update data in a pivot table? Livewire 3
Hi
I have 2 models:
- Recipe.php
- Ingredients.php
And they have ManyToMany relationship using pivot table ingredient_recipe.
Now I want to be able to update data in ingredient_recipe
After preparing ingredients I need to update data in ingredient_recipe and there is 3 situations here:
- new ingredient (so I need to add one new record)
- one ingredient was removed (so I need to delete existing record)
- updated quantity or unit_id
Could you please tell me how the data in pivot tables is updated and how can I handle those 3 situations?
Tables:
create_recipes_table.php:
Schema::create('recipes', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->text('description')->nullable();
$table->string('image')->default('recipes-images/default/default_photo.png');
$table->string('cook_time');
$table->integer('servings');
$table->foreignId('dish_category_id')->constrained('dish_categories')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('cuisine_id')->constrained()->cascadeOnDelete();
$table->foreignId('menu_id')->nullable()->constrained('menus')->cascadeOnDelete();
$table->timestamps();
});
create_ngredient_recipe_table.php::
Schema::create('ingredient_recipe', function (Blueprint $table) {
$table->id();
$table->foreignId('recipe_id')->constrained()->cascadeOnDelete();
$table->foreignId('ingredient_id')->constrained()->cascadeOnDelete();
$table->decimal('quantity', 8, 2);
$table->foreignId('unit_id')->constrained();
$table->timestamps();
});
create_ingredients_table.php:
Schema::create('ingredients', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->timestamps();
});
Would be grateful for some advices
@Dmytro_Shved instead of using attach, you can sync the Ingredients with the Recipe; it should attach/detach/update wherever necessary:
$recipe->ingredients()->sync(
collect($finalIngredients)->mapWithKeys(function ($ingredient) {
return [$ingredient['id'] => [
'quantity' => $ingredient['quantity'],
'unit_id' => $ingredient['unit_id'],
'created_at' => now(),
'updated_at' => now(),
]];
})->toArray()
);
Please or to participate in this conversation.