How to set column as primary key in Laravel model

Updated at 22-Oct-2021, By samar

How to set column as primary key in Laravel model

In this session, we are going to try to solve the "How to set column as primary key in Laravel model" puzzle by using the computer language.

You can set a custom column as primary key in Laravel model. You have to pass the column name to protected $primaryKey property in model class. Now your custom key is treated as primary key of table.
  • Set a column as primary key in Laravel model

    protected $primaryKey = 'userid';
    

    After implementation your code will look like this

    App\Models\User.php
    
    <?php
    
    namespace App\Models;
    
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Support\Facades\Event;
    
    class User extends Authenticatable
    {
            protected $primaryKey = 'userid';
    

    By default, Eloquent models expect for the primary key to be named 'id'. If that is not your case, you can change the name of your primary key by specifying the $primaryKey property. Now your custom key (userid) will be treated as primary key in laravel app.

    It helps you to get the records using eloquent with find() method by passing the value of userid column value. Eg: $user = App\Models\User::find(1); 

    Note: The data type of your custom column (userid) for primary key should be integer. 

Back to code snippet queries related laravel