Laravel

Automatically setting up value in table column using Laravel event listeners

Deep
Written by Deep

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”

And the function definition that will generate UUID. You can declare this function in your custom helper class.

 

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.

 

Leave a Comment