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.

2
  • for random value use this function str_random(); Commented Nov 11, 2015 at 13:00
  • My problem isn't regarding generating a random value but rather how one can be binded to a Laravel model by default Commented Nov 11, 2015 at 13:04

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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)
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;
    });
}

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.