Update many fields of a model

Asked

Viewed 251 times

0

Use the method below to update a table from the form:

public function postEdit(){
    $produto = Produto::find(Input::get('id'));

    $produto->nome       = Input::get('nome');
    $produto->descricao  = Input::get('descricao');
    $produto->quantidade = Input::get('quantidade');
    $produto->valor      = Input::get('valor');

    $produto->save();

    return redirect()->action('ProdutosController@lista');
}

This code is efficient for few fields but imagine an Edit in a table of dozens of fields, I wonder if there is something more functional, in the mold of update_attributes([:entity]) rails.

The create method below is very elegant, if there is something similar to update, kill hard.

public function adiciona(){
    Produto::create(Request::all());

    return redirect()
      ->action('ProdutosController@lista')
      ->withInput(Request::only('nome'));
}

Thank you for your attention.

2 answers

0


Basically you look for the method update:

public function postEdit($id, Request $request){
    $produto = Produto::findOrFail($id);

    $produto->update($request->all());

    return redirect()->action('ProdutosController@lista');
}

Bonus: Improve your route setting. Keep sending id and expecting a Input::get('id') without ensuring that this attribute will be passed is error-prone.

findOrFail will check whether that id exists in the bank, otherwise, error 404 in them.

Take advantage of the controller method injection and pass there what you can use in the specific method, in this case the object $request. Try not to abuse Facades, because there are better ways to solve things...

0

Solved like this:

public function update(ProdutoRequest $request, $id){
  $produto = Produto::find($id)->update($request->all());
  return redirect('produtos');
} 

gmsantos, Thanks for the clarification. I will study your tips.

  • Top! I saw that you are already using Form Request :) You can improve even more using the Route Model Binding and go straight to Product instance

Browser other questions tagged

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