1
1

More than 1 year has passed since last update.

【Laravel】JSONでintegerがstringで返ってしまう

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

Userのroleをenumを使って返していたのでてっきりintegerで返ると思っていたら、JSONの返り値が文字列になっていた。

namespace App\Enums;

enum UserRole: int
{
    case Owner = 1;
    case Admin = 2;
    case Member = 3;
}
{
  "id": 1,
  "name": "山田太郎",
  "avatar": "https://www.gravatar.com/avatar/xxxxxxxxx",
  "role": "2"
}

原因はmigrationファイルでroleをstringにしており、JSONではDBから引っ張ってきているため文字列で返っていた。

解決法

Userモデルに下記を追記する。

app/Models/User.php
protected $casts = [
  'role' => 'integer'
];

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1