Rajen Ghorecha
Rajen Ghorecha

Reputation: 33

Laravel Eloquent : Set custom formatted ID in Table

Is there any way where I can add custom formatted ID on create?

for example, there is a table 'Customers', in this table there are one primary key - 'ID (auto increment)' and one unique key 'customer_id'

Now, when I will create a new customer, the 'ID' is auto increment so it will automatically set in DB.

I want to set 'customer_id' like '2018-0001' at the time of create. CurrentYear-000 INSERTED_ID

Upvotes: 1

Views: 1617

Answers (1)

Remul
Remul

Reputation: 8252

You could use the created model event for this. docs

Eloquent models fire several events, allowing you to hook into the following points in a model's lifecycle: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. Events allow you to easily execute code each time a specific model class is saved or updated in the database. Each event receives the instance of the model through its constructor.

After creating the customer you could generate the customer_id and save it:


Customer.php

use Carbon\Carbon;

class Customer extends Model
{
    protected static function boot()
    {
       parent::boot();

       static::created(function ($obj) {
          $obj->customer_id = Carbon::now()->year.'-000'.$obj->id;
          $obj->save();
      });
    }
}

Upvotes: 1

Related Questions