How to set column as primary key in Laravel model

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.

Answers 1
  • Set a column as primary key in Laravel model

    protected $primaryKey = 'userid';

    After implementation your code will look like this

    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