
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.
-
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';
0By 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.
Random Code Snippet Queries: Laravel
- SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'posts_user_id_foreign'; check that column/key exists
- How to insert value to additional columns in pivot table in laravel
- Composer\Exception\NoSslException
- Delete file from amazon s3 bucket using Laravel
- Call to undefined method Illuminate\Support\Facades\Request::all()
- How to pass data to multiple partial view files in laravel
- How to get specific columns using Laravel eloquent methods
- Get posts belongs to a specific user in Laravel
- Get duplicate records in laravel
- Laravel hasmany select not working
- Create a record if not exist in laravel
- How to implement toggleLike() method in Overtrue\LaravelLike laravel package
- How to access the nth object from Laravel collection object ?
- Get previous date data in laravel
- Send post data from controller to view
- Touch parent updated_at in Laravel
- Post model with title and body in laravel 8
- Update if exist else insert new record in laravel
- Display success message in laravel
- Laravel recursive function in controller
- How to get the id of last record from collection object in laravel view
- How to add columns in existing table using migration in laravel
- SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel8.projects' doesn't exist
- How to check data inserted or deleted in pivot after toggle method
- Trying to get property 'title' of non-object