Update many fields of a model

0

I use the following method to update a table from 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 a few fields but imagine an edit in a table of dozens of fields, I would like to know if there is something more functional, like Rails update_attributes([:entity]) .

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

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

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

Thank you for your attention.

    
asked by anonymous 19.03.2016 / 14:33

2 answers

0

Basically you look for the update method:

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

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

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

Bonus: Improve your route definition. Sending id and expecting Input::get('id') without guaranteeing that this attribute will be passed is prone to errors.

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

Take advantage of the controller's injection of methods and pass on what you can use in the particular method, in this case the object $request . Try not to abuse Facades, as there are better ways to sort things out ...

    
20.03.2016 / 02:57
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'll study your tips.

    
20.03.2016 / 04:08