skip to Main Content

I have a table in MySQL with id column (type varchar) as primary:

enter image description here

and filled table:

enter image description here

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


  1. Chosen as BEST ANSWER

    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:

    protected function casts(): array
    {
        return [
            'id' => 'string',
        ];
    }
    

    I posted it for helping other users (I hope!)


  2. 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

    <?php
     
    class CategoryModel extends Model
    {
        /**
         * The "type" of the auto-incrementing ID.
         *
         * @var string
         */
        protected $keyType = 'string';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search