2

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.

Community
  • 1
  • 1
Petar Vasilev
  • 4,281
  • 5
  • 40
  • 74

3 Answers3

3

Override the save method of your model:

public function save(array $options = array())
{
    if(empty($this->id)) {
        $this->someField = rand();
    }
    return parent::save($options);
}
Dracony
  • 842
  • 6
  • 15
  • Got the following error when I tried the code: ErrorException in User.php line 16: Declaration of App\User::save() should be compatible with Illuminate\Database\Eloquent\Model::save(array $options = Array) – Petar Vasilev Nov 11 '15 at 13:45
1

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;
    });
}
Imtiaz Pabel
  • 5,307
  • 1
  • 19
  • 24
0

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();
Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77