Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在laravel中为api后端返回JSON数据之前定义数据类型_Php_Laravel_Laravel 5.6 - Fatal编程技术网

Php 如何在laravel中为api后端返回JSON数据之前定义数据类型

Php 如何在laravel中为api后端返回JSON数据之前定义数据类型,php,laravel,laravel-5.6,Php,Laravel,Laravel 5.6,我已经开发了一个用于移动设备的api后端。在我把代码放在另一个领域开始开发之前,一切都很顺利。突然,我注意到,user\u id数据类型中的一个已更改为string,它以前的位置是int,所有这些都正常工作 这就是我在laravel控制器中所做的 $clubs=Club::with(['users' => function($q){ $q->select('id','profilePic'); }])->with('leagueCount')

我已经开发了一个用于移动设备的api后端。在我把代码放在另一个领域开始开发之前,一切都很顺利。突然,我注意到,
user\u id
数据类型中的一个已更改为
string
,它以前的位置是
int
,所有这些都正常工作

这就是我在laravel控制器中所做的

  $clubs=Club::with(['users' => function($q){
        $q->select('id','profilePic');
    }])->with('leagueCount')
    ->get();

   return response()->json([
        'success' => true,
        'clubs' => $clubs,
    ],200);
它给了我这样的结果

success: true,
clubs: [
{
id: 8,
user_id: "34",  // this shouldn't be a string. It should be int.
 clubName: "PADELCENTER",
 clubDesc: "Testclub",
 color: "#424242",
 logo: "logotouse.png",
 created_at: "2018-05-12 07:44:40",
 updated_at: "2018-05-12 07:44:40",
 users: {
   id: 34,
   profilePic: "20KdcnX5Gb2dSfunwT8JtmBvcVopDmUwKmQ7XeUI.png"
 },
 league_count: [
 {
   id: 31,
   club_id: "8",
   total: "1"
 }
]
},
您可以看到用户id是一个
字符串
它应该是
int

我是否在模型或其他地方强制设置了数据类型

[注意:user_id为int,在数据库中未签名,作为用户表的外键。]


非常感谢。

您可以使用以下雄辩的变体将属性强制转换为整数:

class Club extends Model
{
    protected $casts = [
        'user_id' => 'integer',
    ];
}

有两种方法可以解决这个问题

在您的模型中,您可以像

$casts = [
'user_id' => 'int'
];
或者您可以使用Resource
php artisan make:Resource Club

然后你可以简单地使用
toArray
方法

  public function toArray($request)
    {
        return [
            // do casting in here
        ];
    }

你应该看看这个。我希望这会有帮助。非常感谢你:)