Shahin
Shahin

Reputation: 283

Creating a Custom ID (Primary Key) in Laravel

I have two tables(models) called Users and Books and need to create custom IDs (primary keys) values for my tables say, u25894r for users and b419k for books. I searched in the internet and stackoverflow a lot but I didn't understand WHERE I should define my custom ID generator function e.g., AppServiceProvider boot function or in Model constructor function. I'd be so appreciate it if you show the way with a little example.

EDIT: I need to write functions that generate unique custom IDs for the tables.

Upvotes: 2

Views: 12788

Answers (3)

WebDev-SysAdmin
WebDev-SysAdmin

Reputation: 369

You need to make a change in both the class/model definition (ie protected $primaryKey = "myUniqueName") and also in the migrations file:

public function up()
{
    Schema::create('recruiters', function (Blueprint $table) {
        // this is in the migration file:
        $table->id('recruiter_id');
        $table->timestamps();
    });
}

Upvotes: 1

Taif Raoof
Taif Raoof

Reputation: 498

You can set the custom id name in the Model class. Use protected $primaryKey = "u25894r"; for user table and then make a migration.

Upvotes: 4

Abdi
Abdi

Reputation: 608

you can set that in migration file

laravel documents is powerful for that you should read about migration from this link

https://laravel.com/docs/5.6/migrations

Upvotes: 0

Related Questions