Access the contents of $ fillable without going through $ fillable. Trying to understand the massive allocation

0

Following a tutorial I have seen that its creator used something he had not seen until now that he was directly accessing the content of the attributes of a class without going directly through the attribute. He told me that this is called massive allocation, I searched for information in laravel's documentation but it must be very basic because it does not specify it well.

An example

Users Model

protected $fillable = ['nombre','apellidos','direccion,'codigo postal','email','contraseña'];


public function emailUsuario()
{
    return $this->email ;
}

There comes my doubt (I do not understand that function), probably the easiest thing in the world and when you make a query to the model from another model such that.

$usuario = New User();
$usuario->email = $request->email

$usuario->save

or

User::create([$request->email])

I understand it much better, however as I say, I understand it when it is from another model but if you try to access the content of an attribute from the same class it is harder to understand it

This is what I do not understand

"return $this->email"

Here we really access the email field as if it were a class attribute, that is, as if the email was like this

protected $email;

but should not it be?

"return $this->fillable["email"]"

Here if we go through the variable fillable

I hope you understand what I want to argue

Can somebody explain to me why we did not pass for fillable and even then it is completely correct?

    
asked by manuellaravelphp 30.08.2017 в 19:01
source

1 answer

0

The vqriable $ fillable is the list of attributes (variables within the class) that you can assign in bulk . Assigning massively simply means that you save the data using a vector (correct me if it is another name but still understood). Example: if your model has attribute1 and attribute2, and $ fillables is:

$fillable = ['atributo1'];

Classic way to save a new model:

$modelo = new Modelo;
$modelo->atributo1 = $var1;
$modelo->atributo2 = $var2;
$modelo->save();

Mass assignment:

$modelo = Modelo::create(['atributo1' => $var1]);

The main difference of each of the two is that the classic mode uses one line of code for each ateibute you use and only one object works at a time, but with the advantage that you can assign values to the attributes even if they are not in the list of $ fillable. On the other hand, the bulk mode can be added in a line of code but will not let you assign values to the attributes that are not in the $ fillable list.  Regarding the function that returns the email, it is well written only that you are confusing the use of the variable $ fillable. That function simply appears because when you show the object of a single line of $ fillable, it appears in the capture or something like that and does not have to do with one another.

    
answered by 12.12.2017 в 19:00