How to generate custom primary id in laravel?

by aniya.jaskolski , in category: Third Party Scripts , 5 months ago

How to generate custom primary id in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 5 months ago

@aniya.jaskolski 

To generate a custom primary id in Laravel, you can override the primaryKey property in your Eloquent model. Here's an example of how you can generate a custom primary key:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class CustomModel extends Model
{
    protected $primaryKey = 'custom_id';

    public $incrementing = false;

    protected $keyType = 'string';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->custom_id = uniqid(); // or any custom logic to generate a unique id
        });
    }
}


In this example, we specify the custom primary key as custom_id and set incrementing property to false since we are not using auto-incrementing IDs. We also specify the key type as string since our custom ID is a string.


In the boot method, we use the creating event to generate a unique custom ID for the model before it is saved to the database. You can customize the logic inside the creating event to generate your desired custom ID format.


Remember to update your migrations to reflect the changes in the model's primary key.