Laravel Model Disable Primary Key & Auto Increment Example

By Hardik Savani April 16, 2024 Category : Laravel

Hi Guys,

This post will give you an example of laravel model disable primary key. I would like to share with you laravel model disable auto increment. I’m going to show you about disable primary key in laravel model. I explained simply about create model without primary key in laravel.

By default laravel migration added id column as the primary key and the model added auto increment it. But if you don't want to add a primary key and auto-increment key for your table then how you will disable it? Laravel provides a way to disable the primary key and auto increment using model properties.

we can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application.

We need to set $primaryKey as a "null" value and $incrementing as "false" to disable the primary key. so, let's see the below model example code:

app/Models/City.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class City extends Model

{

use HasFactory;

/**

* The primary key associated with the table.

*

* @var string

*/

protected $primaryKey = null;

/**

* Disable auto increment value

*

* @var string

*/

public $incrementing = false;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'name', 'state_id'

];

}

I hope it can help you...

Tags :
Shares