I study Laravel and until the end I can not understand the attributes 'fillable', 'hidden' and 'guarded' for mass assignment.

The documentation states that for mass assignment using 'fillable' 'unclean' users can override any parameter for mass assignment. To do this, you need to add a field that you want to protect in 'guarded' and supposedly now you can massively designate 'safe'. Is it so? Then a few questions:

  1. Why not immediately insert all the fields in 'guarded'?
  2. Why the attribute is 'hidden', it is not said about it anywhere ... I noticed that the fields added to 'hidden' are simply not available from the global variable 'Auth'
  3. No problem is better to use:

$flight = new Flight; $flight->name = $anyname; $flight->save(); and everything will be tiptop?

  • 1. Because if you enter all the fields in guarded then you will not be able to change them either, most often id will be entered there. 3. As an option, but this is not a mass appointment. - Anton Kucenko

1 answer 1

  1. Why not immediately insert all the fields in 'guarded'?

The values ​​that would not be added through the mass assignment fall into the guarded , you can add all the guarded fields if you want, but it makes no sense if you use option 3:

 $flight = new Flight; $flight->name = $anyname; $flight->save(); 

It’s just not always possible to directly access the methods, and it’s easier in terms of logic and compactness of the code to work through a mass assignment.

  1. Why the attribute is 'hidden', it is not said about it anywhere ... I noticed that the fields added to 'hidden' are simply not available from the global variable 'Auth'

It hides fields from the output, you looked at the example of User , but if you need to output users to an array or json to send by API or frontend, you just write User:find(1)->toArray() and all attributes will be displayed except hidden , which greatly simplifies your work.

  1. No problem is better to use:

If it is convenient for you, use it, mass assignment is one of the options for saving data, it is not necessary to use it.

  • That is, such fields as, for example: balance, user status, etc., can be easily inserted into 'guarded' and without fear you can assign them en masse? - Alexey
  • one
    On the contrary, if you insert them there - it will not be possible to appoint them en masse, only as you described in option 3. - Yaroslav Molchan
  • one
    @ Alexey prohibits the mass assignment of crucially important attributes that the user suddenly changes by chance, although this does not happen in good applications - Yaroslav Molchan