Laravel Model Disable Auto Increment Code Example

Feb 02, 2023 . Admin



Hi dev,

We'll explain how to disable the main key in a Laravel model in this article. Laravel model deactivate auto increment is something I'd like to share with you. I'll show you how to eliminate the primary key from a Laravel model. How to create a Laravel model without a primary key was clearly explained.

Through a Laravel migration, the id column was added by default as the primary key, and the model added auto increment. But if you don't want to add them, how do you make a table's primary key and auto-increment key inactive? Laravel provides a way to disable the primary key and auto increment using model properties.

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...

#Laravel