Aurora Vollvik
Aurora Vollvik

Reputation: 175

Eloquent: How do I assign values to guarded columns while using the create() method?

Let's say I have an endpoint for user submitted forms. The form input will be stored as a JSON object in a column of a database table, and the user ID will be stored in another. Because I don't want users to be able to somehow set any user ID they want, I've left the user_id column out of the $fillable variable of the Eloquent model.

The create() method accepts an array of key/value pairs to be assigned, but will only assign values to fillable columns. How do I add the user's ID to the guarded user_id column at the same time? Do I have to fetch the last row and update the user ID as a second operation?

Thanks for all help, it's much appreciated.

Upvotes: 6

Views: 7322

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

IF you don't have attribute in $fillable it doesn't mean you cannot fill it.

The $fillable property holds the attributes that could be filled using create() or fill() method but you can still set value for any attributes using property access.

So let's assume you have Model with email, something and else properties. You set $fillable like so:

protected $fillable = ['email', 'something'];

Now let's assume you have data like this:

$data = [
  'email' => '[email protected]',
  'something' => 'foo',
  'else' => 'bar',
];

so now when you use:

Model::create($data);

you will have filled only email and something because those are in $fillable and else won't be filled because it's not, but you can always do something like this:

$model = new Model($data);
$model->else = 'bar';
$model->save();

so you can set here else property value even if it's not inside $fillable but you need to access it like normal property.

Upvotes: 15

Related Questions