Default random value in Laravel models

2020-07-24 05:52发布

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.

3条回答
趁早两清
2楼-- · 2020-07-24 06:02

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;
    });
}
查看更多
仙女界的扛把子
3楼-- · 2020-07-24 06:06

Override the save method of your model:

public function save(array $options = array())
{
    if(empty($this->id)) {
        $this->someField = rand();
    }
    return parent::save($options);
}
查看更多
一夜七次
4楼-- · 2020-07-24 06:18

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();
查看更多
登录 后发表回答