Hi Guys, sometimes we need to set some calculated or default value in table while creating a new record in database’s table. Using laravel you can set an event listener within the specific model, which will automatically insert the value in table column.
Laravel provides different type of event listeners, are as : creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored.
For example here we are going to create an event listener for generating and inserting UUID automatically for a new record in table.
Say in model named “User”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use HasApiTokens, Notifiable; //This will use full UUID instead of int as primary key public $incrementing = false; /** * Define model event callbacks. * * @return void */ protected static function boot() { parent::boot(); //Generate and set UUID automatically for the user static::creating(function($user) { $user->id = gen_uuid(); }); } } |
And the function definition that will generate UUID. You can declare this function in your custom helper class.
1 2 3 4 5 6 7 8 9 10 11 12 | /** * Generate a UUID * @return string */ if (!function_exists('gen_uuid')) { function gen_uuid() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } } |
The above event handler will now set UUID automatically for new user record. You do not have need to manually generate a new UUID at the time of creating / registering User. This event handler will automatically do that for you.