Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
Aurora Vollvik Avatar asked Apr 17 '16 15:04

Aurora Vollvik


1 Answers

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.

like image 164
Marcin Nabiałek Avatar answered Sep 23 '22 01:09

Marcin Nabiałek