Eloquent firstOrCreate documentation or usage
The create() method does mass assignment and this is a big security issue, so Laravel has a protection against it. Internally it has guarded = ['*'], so all your columns will be protected against mass assignment. You have some options:
Set the fillable columns of your model:
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}
Or set only the ones you want to keep guarded:
class User extends Eloquent {
protected $guarded = array('password');
}
You may, at your own risk also do:
class User extends Eloquent {
protected $guarded = array();
}
And everything will be unguarded.
Take a look a the docs: http://laravel.com/docs/eloquent#mass-assignment
You also could use your Facade to call it:
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return Settings::firstOrCreate(array('name' => $settingName));
}
}
Comments
-
Clark T. almost 2 years
I'm attempting to seek a table to see if a column named "name" exists if so return the value and if not create that row with a null value i saw firstOrCreate but i cannot figure out how to use it for the life of me.
This is what i currently have, can someone lend a hand?
class Settings extends Eloquent { protected $table = 'settings'; protected $primaryKey = 'name'; public static function get($settingName) { return self::firstOrCreate(array('name' => $settingName)); // return self::select(array('value'))->where('name', '=', $settingName)->first()->value; } }
-
Clark T. over 10 yearsthe issue I'm having is when calling Settings::get('example'); and exam example doesn't exist in the database instead of creating it i get a MassAssignmentException of name
-
Clark T. over 10 yearsAlso why would calling by my Facade be better than using self:: ?
-
Antonio Carlos Ribeiro over 10 yearsYou are in fact mass assigning, so you need to add
protected $guarded = [];
to your model, if you need to assign to all your columns. -
Clark T. over 10 yearsim not attempting to mass assign all i want to do is if that name is not in the table already create a row with names value set to $settingName is that not what my code reflects?
-
Antonio Carlos Ribeiro over 10 years
create()
method does mass assignment by itself. Have you tested setting the guard var? -
Clark T. over 10 yearsI have not what column would i guard the table only contains the timestamp columns a name and value columns?
-
Antonio Carlos Ribeiro over 10 yearsStart by guarding nothing (
$guarded = [];
), to test mate. Then you move to what you really need. -
Clark T. over 10 yearsNevermind i see what you meant, and that worked perfectly, could you share why that made it work so i'll know in the future?
-
Clark T. over 10 years