Update record with Laravel 5.2?

4

I have the following function:

public function alterar($id)
{
    $produto = Produto::find($id);
    $params = $request->all();
    $produto->fill($params)->save();
    return redirect()->action('ProdutoController@index');
}

however every time I change a product, a new one is added to the database (a new updated copy) and the old one is still there, so what is happening is a copy and not actually updating that product?

    
asked by anonymous 03.08.2016 / 23:42

3 answers

0

You could verify that the item was actually set and that it exists with the public property $ exists :

public function alterar($id)
{
    $produto = Produto::find($id);
    if ($produto && $produto->exists)
    {
        $params = $request->all();
        $produto->fill($params)->save();
    }
    return redirect()->action('ProdutoController@index');
}

Your question seems to me to be as strange as it is, perhaps a more thorough investigation into routes and Controller to see if you have any wrong calling code would be a good idea of what might be happening. / p>

Reference public $ exists = false;

    
13.10.2017 / 01:43
0
public function update($id)
{
    $produto= Produto::find($id);
    $produto->update(Input::all());
    return view('suaView');
}

Remembering to have the $ fillable fields registered in the model for Mass Assignment to work right and safe.

You should also add the appropriate route, for example:

Route::post('produto/{id}', 'ProdutosController@update');

I hope I have helped.

    
16.05.2018 / 23:49
-1

Instead of using find , use findWhere , maybe it's the solution.

    
15.08.2016 / 22:06