Update registration with Laravel 5.2?

Asked

Viewed 684 times

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');
}

but every time I change a product, a new one of it is added in the bank (a new updated copy) and the old one is still there, so what’s happening is a copy and not effectively updating that product?

  • Is the id you are receiving correct with the search in the bank? Try to use findOrFail instead of find to see if any mistakes are made

  • Check if the database does not have any Rigger doing Insert because I see no error in your code.

  • Instead of using find, use findWhere, maybe that’s the solution.

3 answers

0

You can do it that way

public function update(Request $request, $id)
{
   $produto = Produto::findOrFail($id);
   $produto->update($request->all());
   return view('view');
 }

0

You could check whether the item has actually been set and whether the same 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 doubt seems to me as well as strange, perhaps a larger investigation into the routes and Controller to see if there’s any code calling wrong would be a good idea of what might be going on.

Reference: public $exists = false;

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 properly and safely.

You should also add the appropriate route, for example:

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

I hope I’ve helped.

Browser other questions tagged

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