I have a table in MySQL with id column (type varchar) as primary:
and filled table:
I use Laravel for backend. I created Model for this table and put this code inside Model class:
protected $fillable = [
'id',
'titleEn',
'titleFa',
'icon',
'sortOrder',
];
And in the controller.index, I have:
$categories = CategoryModel::all();
return $categories;
When I call this API, the response shows 0 value for id instead of real value:
[
{
"id": 0,
"titleEn": "Computer",
"titleFa": "کامپیوتر",
"icon": "",
"sortOrder": 0
},
{
"id": 0,
"titleEn": "Novel",
"titleFa": "رمان و داستان",
"icon": "",
"sortOrder": 1
}
]
What is the problem an how can I deal with without renaming id to another name? Thanks.
Note:
In my case, primary key is id with different datatype.
2
Answers
As I added note in my question, In my case, primary key is id with different datatype. But suggested links by my friends is about another primary column with different name from id (Thanks).
The suggested links helped me to solve the problem. I used casts function in Model:
I posted it for helping other users (I hope!)
You can do one think .. define the keyType as string in modal. Which you are using. it will automatically accept the string primary key.
https://laravel.com/docs/7.x/eloquent