Best practice for Mass Assignment

-2

In order to obtain the facilities that the framework proposes, in the specific case of writing data to a table in a database, we can use the 'mass assignment' feature, which means, in free translation, 'mass insertion ( of data) '.

I followed a tutorial, and I understood that, starting from a fairly simple principle, the goal is reached.

My scenario consisted of a form (source of the data to insert), a method in a controller, a class that inherited 'Model' and, of course, a database.

But when I ran the routines, I saw that the database accepted the recording but did not fill the columns. That is, the record existed, but all in white.

I think you have discovered the problem, but I wonder if the solution is the best one.

First, it was like this, while there was a blank recording problem:

Name of the table in the database: 'products'
Fields in this table: id, name, description, value, quantity. Data source form (I removed the 'fat', leaving the essential):

<form action="{{action('controllerTeste@adiciona')}}" method="post">
    <input type="hidden" name="_token" value="{{{csrf_token()}}}"/>
    <input name="namNome"/>
    <input name="namDescricao"/>
    <input name="namValor"/>
    <input name="namQuantidade" />
    <button type="submit">Salvar</button>
</form>

To reinforce the above understanding, the field with the 'hidden' attribute is necessary so that there is no impediment to writing to the table.

The method that triggered the recording:

public function adiciona(){
        $params = Request::all();
        $produto = new Produto ($params);
        $produto->save();
        return redirect()->action('controllerTeste@lista')->withInput();
    }//adiciona

The class that inherits 'model':

<?php
namespace tempo;
use Illuminate\Database\Eloquent\Model;
class Produto extends Model
{
    protected  $table = "produtos";
    public $timestamps = false;
    protected $fillable = array('nome','descricao','valor','quantidade');
}
?>

From the perceived error, I began to imagine how Laravel would be able to know, by what is written in the controller, how to associate each data that came from the form to the correct column in the database.

The $ fillable variable in the Product class was clear, but the arrival of the data came from the controller, through the variable $ params, which did not say anything about which form field and in what order it related to $ fillable .

It was at this point that I 'mistrusted' the names of the fields in the form. For my convenience to separate attribute names, all fields belonging to 'name' would start with 'nam' and all 'id' attributes would have identifiers starting with 'id' in the same way.

I then changed the form field names to exactly match the column names in the database.

That's where it all worked.

Then I wondered, but will I be required to put names on forms always under this rule? Would not there be some kind of 'alias' for each form field that could be translated to the name of the columns in the target table?

I searched the web and, after some research, found a code that worked.

To apply it, I returned the form names to my traditional way of writing them, and rewrote the method in the controller to 'translate' the names of that form into the target table column names.

The controller method looks like this:

 public function adiciona(){
    $produto = Produto::create(array(
      'nome' =>Request::input('namNome'),
      'descricao'  => Request::input('namDescricao'),
      'valor'   => Request::input('namValor'),
      'quantidade' => Request::input('namQuantidade')));
    $produto->save();
    return redirect()->action('controllerTeste@lista')->withInput();
}//adiciona

What was replaced in the controller routine was to replace

$params = Request::all();
$produto = new Produto ($params);

by

$produto = Produto::create(array(
          'nome' =>Request::input('namNome'),
          'descricao'  => Request::input('namDescricao'),
          'valor'   => Request::input('namValor'),
          'quantidade' => Request::input('namQuantidade')));

So, I reiterate what is written in the title of this question: is it the best practice?

    
asked by anonymous 22.05.2016 / 14:21

1 answer

1

It is not necessary to write as much, do the following with your method adds:

public function adiciona(Request $request){
    //capturar todos os dados do form
    $dadosFormulario = $request->all();
    //fazer insert
    $produto = Produto::create($dadosFormulario);
    return redirect()->action('controllerTeste@lista')->withInput();
}

In your model you need to declare your primary key, do the following:

protected $primaryKey = 'chave_primaria';
    
30.05.2016 / 20:59