Support the ongoing development of Laravel.io →
Security Database Eloquent
Last updated 2 years ago.
0

Is there a way from the code without manually assigning IDs from the code to create child objects?

Try something like that:

$comment = new Comment(array('message' => 'A new comment.'));

$article = Article::find(1);

$comment = $article->comments()->save($comment);

But, i think foreign keys should not be guarded. Guarded - is a protection against the mass assignment.

Last updated 2 years ago.
0

AFAIK, fillable/guarded applies ONLY to the model's fill() method and, as a consequence, to the model's constructor if arguments are passed, and finally to the model's create() method.
If you're going to use one of those three (i.e. mass assignment), you MUST declare either a fillable or a guarded array, otherwise you'll get an exception. In any other case, instead, you just don't worry about.

Now, foreign keys should never be "mass assignable", so they really should be either included in the guarded array or excluded from the fillable array. Again, you are not required to do this if you don't use mass assignment (but I think it's good practice anyway).

tbergeron said:

  • 1: How would I do this if comment.article_id is guarded? (I cannot assign anything to it).

[ ... ]

  • 3: If I don't specify anything for a certain field. What's the defaults? Will it be visible and fillable by default?

  • 4: Should id and timestamps be guarded or hidden?

  1. indeed, as said, you can assign a guarded (not fillable) attribute; again, you just can't set it via mass assignment - i.e. you can't use fill(), constuctor with arguments, or create() to set the guarded attribute, but any other way is ok.

  2. As said, there is no default for fillable/guarded: it comes in action only with one of the aforesaid three methods for mass assignment, and in that case you must explicitly declare the value. Instead AFAIK the default for visible/hidden is ALL VISIBLE.

  3. They should be guarded (not fillable), of course. If you like, you can make them hidden, too, but normally it's not a security problem.

Last updated 2 years ago.
0

Thanks a lot, this answers all of my questions! :D

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

tbergeron tbergeron Joined 6 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.