Laravel 5.3从关联数组中获取布尔值

时间:2017-01-18 03:40:56

标签: php object indexing eloquent laravel-5.3

我有ImageController这样:

$image = Image::where('id', $id)->first();

return [
    'image' => $image,
    'image_360' => $image['360']
];

前面的行返回浏览器:

{
    "image": {
        "id": 1,
        "name": "default.jpg",
        "360": 1,
    },
    "image_360": null
}

Image迁移:

$table->increments('id');
$table->string('name');
$table->boolean('360');

Image型号:

class Image extends Model
{
    protected $fillable = ['name', '360'];

    protected $casts = [
        '360' => 'boolean'
    ];
}

为什么$images['360']如果值为null会返回true

1 个答案:

答案 0 :(得分:1)

以下是解决方法:我尝试了很多方法,但无法直接获取数字值,如post

中所述
return [
    'image' => $image,
    'image_360' => array_values($image->toArray())[2];
];