Skip to content

All topics  /  General

How to Model Disable Primary Key & Auto Increment Tutorial?

General ·

Hi dev,

In this article, we'll show you how to disable the main key in a Laravel model. I'd like to share laravel model deactivate auto increment with you. I'm going to demonstrate how to remove the main key from a Laravel model. I gave a clear explanation of how to create a Laravel model without a primary key.

Id column was added by default as the primary key through laravel migration, and the model added auto increment. However, how can you make a table's main key and auto-increment key inactive if you don't want to add them? Using model properties, Laravel offers a method to turn off the primary key and auto increment.

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'
    ];
}