class User extends ActiveRecord\Model { public function generateAuthKey() { $authKey = Yii::$app->security->generateRandomString(); $this->auth_key = $authKey; $this->save(false); return $authKey; } } $user = new User(); $user->name = 'John Doe'; $user->email = 'johndoe@example.com'; $user->password = 'mysecretpassword'; $user->generateAuthKey();
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class User extends Model { protected static function boot() { parent::boot(); static::creating(function ($model) { $model->auth_key = Str::random(32); }); } //... } $user = new User(); $user->name = 'Jane Doe'; $user->email = 'janedoe@example.com'; $user->password = 'mysecretpassword'; $user->save();In this example, we have a `User` model in an application built using Laravel framework. The `generateAuthKey` function is achieved using the `creating` event which is triggered when the user is being created. The `auth_key` attribute is set with a random string generated using the `Str::random` function provided by Laravel's `Illuminate\Support` package. The function is triggered automatically when a new user is saved to the database. Package/library used in Example 1: Yii framework (https://www.yiiframework.com/) Package/library used in Example 2: Laravel framework (https://laravel.com/) with its `Illuminate\Support` package.