T. Cem Yılmaz
T. Cem Yılmaz

Reputation: 510

How to update Laravel relation's table

There are 2 models:

Product and Product_Images

class Product extends Eloquent { 
    protected $guarded = [];
    public $timestamps = true;

    public function images(){
        return $this->hasMany('product_image');
    }

    public function brand(){
        return $this->belongsTo('brand');
    }
}

class Product_Image extends Eloquent { 
    protected $table = 'product_images';
    protected $guarded = [];

    public function images(){
        return $this->hasMany('product_image');
    }
}

I can do update or insert data to this models

$product = new Product;
$product->title = $data['title'];
$product->alias = $data['alias'];
$product->short_description = $data['short_description'];
$product->price = $data['price'];
$product->brand_id = $data['brand_id'];
$product->description = $data['description'];
$product->published = 1;
$product->save();
foreach($data['images'] as $k => $v){
    if($data['main'] == $k){
        $product->images()->save(
            new Product_Image(['image' => $v,'main' => 1])
        );  
    }else{
        $product->images()->save(
            new Product_Image(['image' => $v,'main' => 0])
        );
    }
}

but when users try to edit the product, users may delete the existing images and try to add new ones and send the form. Which way should I follow for update the images relations. Should I delete all images related to product and create new ones ? this looks like bad practice to me, is there any best for this?

Upvotes: 0

Views: 191

Answers (1)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5186

First of all your relation is wrong I think you have a one to many relation with product and image

so this should be

public function images(){
    return $this->hasMany('product_image');
}

public function product()
{
    return $this->belongsTo(Product::class);//import your product class with use
}

Also you are wrongly defining your relations. In your relation you will define the class optionally in some situations you can pass foreign key and local key and table names see Defining Relationships

This should be

public function images(){
    return $this->hasMany('product_image');
}
public function brand(){
    return $this->belongsTo('brand');
}

This

public function images(){
    return $this->hasMany(Product_Image::class);//import class
}
public function brand(){
    return $this->belongsTo(Brand::class);//import Brand class
}

Also you can simplify your code here

       if($data['main'] == $k){
            $product->images()->save(
                new Product_Image(['image' => $v,'main' => 1])
            );  
        }else{
            $product->images()->save(
                new Product_Image(['image' => $v,'main' => 0])
            );
        }


        $product->images()->save(
            new Product_Image(['image' => $v,'main' => (int)($data['main'] == $k)])
        );

Upvotes: 1

Related Questions