Laravel Update With Relationships - Good practice

1

I created an Update for a Products table that is related to another table that is the Product (product_info) for this product. But when I do Update I change the Product information, I delete the article and re-create an article with the same or new content. It's all working fine but I wanted to know if it's a good programming practice or if there is another way.

Basically this is it:

Controller:

$product = Product::find($id);
$product->display_name = Input::get('name_display');
$product->save();

$product->Product_info()->delete();

$product_info = New Product_info;
$product_info->name = Input::get('name');
$product_info->description = Input::get('description');
$product_info->Product()->associate($product);
$product_info->save();

Model: Product.php

public function Product_info()
{
    return $this->hasOne('App\Product_info');
}

PS: If I was not explicitly let me know.

    
asked by anonymous 14.10.2016 / 19:06

1 answer

1

I would use the same instance, $produto->Product_info() if it exists, otherwise, I would create what you are doing.

$product = Product::find($id);
$product->display_name = Input::get('name_display');
$product->save();  

$product_info = $product->Product_info();
if (!$produto_info) 
{ 
    $product_info = New Product_info;
    $product_info->Product()->associate($product);
}
$product_info->name = Input::get('name');
$product_info->description = Input::get('description');
$product_info->save();

If the relationship is mandatory at the time of registration, that is, the registration of product is done and product_info can use a update :

$product = Product::find($id);
$product->display_name = Input::get('name_display');
$product->save();  

$product->Product_info()->update([
    'name' => Input::get('name'),
    'description' => Input::get('description')
]);
    
14.10.2016 / 19:15