I am trying to use email as my table's primary key, so my eloquent code is-
<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserVerification extends Model { protected $table = 'user_verification'; protected $fillable = [ 'email', 'verification_token' ]; //$timestamps = false; protected $primaryKey = 'verification_token'; }
And my DB is like this-
but if I do this-
UserVerification::where('verification_token', $token)->first();
I am getting this-
{ "email": "[email protected]", "verification_token": 0, "created_at": "2016-01-03 22:27:44", "updated_at": "2016-01-03 22:27:44" }
So, the verification token/primary key becomes 0.
Can anyone please help?
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.
Consider upgrading your project to Laravel 9.x . The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.
Laravel also allows you to define a custom Pivot model. To define a custom model, first create your own "Base" model class that extends Eloquent. In your other Eloquent models, extend this custom base model instead of the default Eloquent base.
The "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a table property on your model:
This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.
When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.
By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790
So the solution is:
class UserVerification extends Model { // if your key name is not 'id' // you can also set this to null if you don't have a primary key protected $primaryKey = 'your_key_name'; public $incrementing = false; // In Laravel 6.0+ make sure to also set $keyType protected $keyType = 'string'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With