我的Eloquent查询是:
$postcode = address::where('client_id', $bill->client_id)->where('label', $bill->location)->select('postcode')->get();
echo $postcode
返回[{"postcode":"LS18 2DY"}]
如何只返回邮政编码字符串?
$postcode->postcode
或$postcode['postcode']
失败
答案 0 :(得分:2)
[{"postcode":"LS18 2DY"}]
是对象数组。
由于您使用了->get()
,因此您将返回多个将被包装到数组中的项目。
将其限制为一个项->first()
$postcode = address::where('client_id', $bill->client_id)->where('label', $bill->location)->select('postcode')->first();
第二种方式,将是
$postcode[0]->postcode
我建议使用 first()
而不是添加索引。
查看Laravel文档retrieving a single row
答案 1 :(得分:0)
get()返回一个数组,你应该使用get(1)或first()来获取一个元素,或者使用foreach来触发数组。
$postcode = address::where('client_id', $bill->client_id)->where('label', $bill->location)->select('postcode')->get(1);
$postcode->postcode;
答案 2 :(得分:0)
使用toArray()将收集对象转换为数组,然后使用foreach访问每个数据
$data = some collection;
foreach($data->toArray() as $single_data)
{
echo $single_data['key for each data'];
}