0

I am trying to populate two columns with random strings whenever a new user is created in laravel

maybe something like this in User model

public function putStringInDatabase () {
    $this->public_key = str_random(40);
}

and whenever a new row is added in users table public_key and private_key columns get updated automatically by that random string

Muhammad
  • 921
  • 2
  • 11
  • 29

3 Answers3

1

Take a look at Model Events. Specifically creating.

For example:

User::creating(function($user) {
    $this->public_key = str_random(40);
    $this->private_key = str_random(40);
});
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

http://php.net/manual/en/function.uniqid.php

Try making the string unique!

rardoz
  • 112
  • 10
0

You could do it in the controller when you are creating the record

/**
 * Create a new Object instance.
 *
 * @param array $data
 *
 * @return Object
 */
protected function create(array $data)
{
    $object = new Object([
        'fields' => $data['values']
        'email' => $data['email'],
    ]);
    $object->public_key = str_random(40);
    $object->save();

    return $object;
}

This will let you add a public_key outside of the mass assignment.

Dimitri Acosta
  • 1,756
  • 12
  • 15
  • I can do it but I have used this same function in several places throughout my application so to save the time I want something smart which can add the random string in defined column whenever I create a record in database – Muhammad Aug 09 '15 at 19:37
  • Why don't you try to create a helper for that? – Dimitri Acosta Aug 09 '15 at 20:28