I am trying to set up a random default value for a Laravel model so that when a user registers a random value is saved to the database for each user.
I've looked at similar question on StackOverflow which explains how to setup a default value using the $attributes variable but it doesn't explain the random bit.
Override the save
method of your model:
public function save(array $options = array())
{
if(empty($this->id)) {
$this->someField = rand();
}
return parent::save($options);
}
For bind a field default when save model follow this
public static function boot()
{
parent::boot();
static::creating(function($post)
{
$post->created_by = Auth::user()->id;
});
}
You're not providing enough info, so I'm giving you a solution: you can use a MUTATOR in your User Model:
class User extends Model {
public function setRandomStringAttribute($number)
{
$this->attributes['random_string'] = str_random($number);
}
}
Where "random_string" is the column in your user table that holds the value. In this way each time you set the "random_string" property of a Model it's automatically set as defined. You simply use it like this:
$user = new User;
$user->random_string = 20;
$user->save();