Reputation: 537
Well, I am using Laravel 5.4 and reached in a situation where I need to update one to many (hasMany) relation ship.
I have a products
table and a product_images
table. Below is my relation definition in each model.
//Product.php
public function productImages()
{
return $this->hasMany('App\ProductImage');
}
//ProductImage.php
public function product()
{
return $this->belongsTo('App\Product');
}
I am giving a form interface to update existing product. In that I have 4 optional file upload input html tag for updating or adding (new) images for the product. Remember all these 4 image upload is optional.
So my question is what is the best approach(laravel way) to
product_images
tableI know the attach
or detach
method (sync
) to remove all and then add the provided one. But I want to maintain the id if we are replacing any existing image.
Upvotes: 7
Views: 9631
Reputation: 531
Old question, but here's an answer.
1 and 2 - Laravel's updateOrCreate() method will update existing records and insert new records if an existing image ID is not provided. See "updateOrCreate" under Eloquent ORM's Update documentation.
$images = App\ProductImage::updateOrCreate(
['id' => $id],
['field1' => $field1, 'field2' => $field2]
);
3 - To delete, add a delete checkbox to your form which passes target image IDs as an array...
<input type="checkbox" name="imgsToDelete[]" value="{{$product->image->id}}">
<label>Delete</label>
...then, in your product update method, simply pass the field array to Eloquent's destroy() method.
$imgsToDelete = $request->get('imgsToDelete');
ProductImage::destroy($imgsToDelete);
Don't forget to delete stored images from the file system!
Upvotes: 3