Ravindra24.com

How to Generate Custom Unique ID in Laravel

The unique ID can be important part of any web application because it uniquely identify the record by that particular id and this unique id can be used for many purpose. Some people like to generate unique id as auto incremental and someone like to generate unique id in custom format. This custom id can be collection of numeric and alphabet.

Step 1

To generate unique id in Laravel, You need to install ID Generator package in Laravel command prompt so following is the command to install that package.

composer require haruncpi/laravel-id-generator

Step 2

You can use this ID Generator in controller or model by importing it.

use Haruncpi\LaravelIdGenerator\IdGenerator;
$id = IdGenerator::generate(['table' => 'users','field' => 'property_id', 'length' => 4, 'prefix' =>'PR']);

table is used to give the name of table where you want to generate the Unique Id, field is used to give the column reference for which you want to generate custom unique id. If you don’t give reference column name, it will be applied on default id column.length is used to define the number of digits which you want to display in you custom id format.prefix is used to display something which required to be prefixed.

public function registration_submit(Request $request)
{
	$id = IdGenerator::generate(['table' => 'users','field' => 'property_id', 'length' => 4, 'prefix' =>'PR']);
        
            $hotel_user = new User();
            $hotel_user->property_id = $id;
            $hotel_user->property_name = $request->property_name;
            $hotel_user->email = $request->email_address;
            $hotel_user->password = bcrypt($request->password);
            $hotel_user->status = 0;
            $hotel_user->remember_token = $randToken;
            $res = $hotel_user->save();

}

Variable $id has the custom unique id which is generated by IdGenerator::generate() function and it will be inserted into property_id column.If you want to generate unique id for ID column then make this id folumn fillable into your model and define public $incrementing =false; in your migration file.

Leave a Comment