Laravel Update With Relationships - Good Practice

Asked

Viewed 887 times

2

I created an Update for a Products table that is related to another table that is the Article(product_info) of this product. Only when I do Update I change the Product information, delete the article and create an article with the same or new content. Everything is working perfectly but I wanted to know if it is 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 haven’t been explicit, let them know.

  • 1

    I wouldn’t delete Produto_info(), I would use the same instance and save the new information, ie, update!

  • @Virgilionovic The problem is I’ve tried it in many ways and this is the only one that didn’t give me any trouble.

  • link data are mandatory? if there is a product there is also product_info?

  • well anything post the layout of the tables if the answer doesn’t work out and the complete layout of the model Produto and Product_info.!

1 answer

2


Would use the same instance, $produto->Product_info() if there is, if not, 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, ie, It is made the registration of product 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')
]);
  • 1

    Thanks, I was unaware of Function update()! I think it looks better this way!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.