1

I'm using foreignId in my migration and it is converting to string, but primary key is working fine.

By the way I'm using Laravel 8, PHP 8

this is my migration

Schema::create('tokens', function (Blueprint $table) {
 $table->id();
 $table->foreignId('shop_id');
 $table->timestamps();
});

then if I want to convert this model to json

$token = Token::find(1);
return response()->json($token, 200);

I will receive this

{
 id: 1,
 shop_id: "12",
 created_at: "2021-06-08T12:41:07.000000Z"
 updated_at: "2021-06-08T12:41:07.000000Z"
}

3 Answers3

1

I'm not sure why your shop_id is a string but I guess your tokenController is saving the shop_id property as a string.

Anyway, if you want to make sure your Token model always return the shop_id property as an integer, you should tell your model to cast it to an integer.

In your Token model, add the following line just after your class declaration:

protected $casts = ['shop_id' => 'integer']);

See Laravel Attribute Casting Documentation

LobsterBaz
  • 1,752
  • 11
  • 20
1

Solved this by enabling nd_pdo_mysql extension and disabling nd_mysqli extension in configuration. Thank you all for help.

0

you can make it with 2 solution

Solution 1
you can create resource and customize response

run php artisan make:resource TokenResource

and in toArray funcation

public function toArray($request)
{
    return [
        "id" => intval($this->id),
        "shop_id" => intval($this->shop_id),
        "created_at" => strval($this->created_at),
    ];
}

and in controller

$token = Token::find(1);
return TokenResource($token);

Solution 2
using stdClass

$response = new \stdClass;
$response->id = intval($token->id);
$response->shop_id = intval($token->shop_id);
return response()->json($response,200);

M.ramadan
  • 15
  • 7