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": "sdfsdf@sdfsdf.sdf",
"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?
Theres two properties on the model you need to set. The first
$primaryKey
to tell the model what column to expect the primary key on. The second$incrementing
so it knows the primary key isn't a linear auto incrementing value.For more info see the
Primary Keys
section in the documentation on Eloquent.keep using the id
and get the email :
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:
On the model set
$incrementing
to falseThis will stop it from thinking it is an auto increment field.
Laravel Docs - Eloquent - Defining Models