Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent firstOrCreate documentation or usage

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;
                }
        }
like image 839
Clark T. Avatar asked Oct 25 '13 14:10

Clark T.


1 Answers

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));
        }
 }
like image 190
Antonio Carlos Ribeiro Avatar answered Nov 13 '22 16:11

Antonio Carlos Ribeiro