0

When creating a user within User.php I'm trying to define a UUID, create a directory, and then add it to the user on the DB. The folder creates successfully with the UUID but it will not get passed into the creating() callback.

/**
    * Create the user when this class is called
    *
    * @return void
    */
public static function boot()
{
    // Setup parent
    parent::boot();

    // Create UUID
    $uuid = Str::uuid();

    // Create user directory on S3
    Storage::disk('s3')->makeDirectory('users/' . $uuid);

    // Assign UUID to new user
    self::creating(function ($model) {
        $model->id = $uuid;
    });
}

$model->id = $uuid; is undefined here and results in no value.

Joe Scotto
  • 10,936
  • 14
  • 66
  • 136
  • how do u create the user, plz post the code. and is `id` string? – TsaiKoga Mar 12 '20 at 05:14
  • I'm using the default Laravel registration features... If I pass the `Str::uuid()` direct into the creating callback, it will get added... I believe this has something to do directly with the scoping of my variables and callback function – Joe Scotto Mar 12 '20 at 05:19

1 Answers1

3

Inject the $uuid into closure like this:

self::creating(function ($model) use ($uuid) {
        $model->id = $uuid;
    });
TsaiKoga
  • 12,914
  • 2
  • 19
  • 28
  • Wow, that was easy... I tried `use $uuid` but hit an error, the parenthesis fixed it... 1:30 AM brain doesn't work the best sometimes. – Joe Scotto Mar 12 '20 at 05:31