samedi 19 août 2017

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.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2x1mQwO
via IFTTT

Aucun commentaire:

Enregistrer un commentaire