Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to UPDATE one to many (hasMany) relation in Laravel 5

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

  1. update existing entries in product_images table
  2. add new one if provided
  3. delete existing if it is removed

I 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.

like image 989
sanjay ojha Avatar asked Aug 19 '17 19:08

sanjay ojha


1 Answers

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!

like image 72
Chad Kieffer Avatar answered Sep 22 '22 02:09

Chad Kieffer