Goal
Create a booking system where each new booking gets a unique auto-generated bkg_id
in the format BKG-00000001
, BKG-00000002
, and so on.
Step 1: Create the Model and Migration
Run this command to create a model and migration for the sequence table:
Step 2: Define Your Migrations
database/migrations/YYYY_MM_DD_create_sequence_tbls_table.php
database/migrations/YYYY_MM_DD_create_bookings_table.php
database/migrations/YYYY_MM_DD_create_generate_id_trigger.php
This migration sets up a MySQL trigger to generate the bkg_id
.
Step 3: Run the Migrations
After creating all the migrations, run this command:
This will:
-
Create the
sequence_tbls
table to track the ID sequence -
Create the
bookings
table -
Add a trigger to automatically generate a formatted
bkg_id
Notes
-
The trigger uses
LAST_INSERT_ID()
to fetch the latest ID inserted intosequence_tbls
, then pads it to 8 digits and prefixes it withBKG-
. -
Make sure your MySQL user has permission to create triggers.
-
This solution doesn't rely on Laravel logic for generating the ID — it's handled directly by MySQL.
Example: Inserting a Booking
You can test by inserting a new booking record using Laravel’s tinker or a controller:
After creation, the the bkg_id
field will look like this: BKG-00000001
Let me know if you'd like:
-
A full CRUD controller
-
Postman collection to test
-
Blade UI or API setup