如何使用laravel打印json数据

如何使用laravel打印json数据,laravel,Laravel,我是新来的 [{ "id":1, "name":"demo", "slug":"demo", "status":1, "get_total_record":{ "store_id":1, "counts":2 } }] 这是我的数据库记录 如何打印计数值 我正在使用$get\u total\u record->counts,但它给出了错误。您正在从控制器返回一个变量。我们叫它$post。您可以这样显示 {{ $po

我是新来的

[{
    "id":1,
    "name":"demo",
    "slug":"demo",
    "status":1,
    "get_total_record":{
        "store_id":1,
        "counts":2
    }
}]
这是我的数据库记录

如何打印计数值


我正在使用
$get\u total\u record->counts
,但它给出了错误。

您正在从控制器返回一个变量。我们叫它
$post
。您可以这样显示

{{ $post->get_total_record->counts }}

如果它已经是json,那么假设您将其保存在变量$tests中,请尝试:

foreach($storeLists as $sl){
    if(isset($sl->get_total_record)){
        if(isset($sl->get_total_record->counts)){
            echo $sl->get_total_record->counts;
        }
    }
}

如果您有模型的实例:

{{ json_decode($demo->get_total_record, true)['count'] }}
如果您有一个集合,则需要对其进行迭代:

@foreach ($demos as $demo)
    {{ json_decode($demo->get_total_record, true)['count'] }}
@endforeach
或者,您可以在
get_total_record
字段中使用:

protected $casts = [
    'get_total_record' => 'array',
];
并通过以下方式访问数据:

{{ $demo->get_total_record['count'] }}

你可以这样做。实际上,您正在使用关系并从关系变量中直接获取计数,这不可能是一种错误的方式,请遵循以下步骤。请分享你的结果

$store=new Store;
$storeList=Store::with('getTotalRecord')->get();
//已编辑,现在您必须循环浏览商店列表,这是为了便于理解

foreach($storelist as $store){
  echo "Count is: ".$store->getTotalRecord->count()."<br />";
}
foreach($storelist作为$store){
echo“Count是:“.$store->getTotalRecord->Count()”
”; }
您做了什么,您得到的是Json字符串?您可以分享您的方法/代码吗?json字符串中有多条记录,json字符串可以,但只有Y个显示问题。我不知道怎么打印。我还在视图中使用foreach()循环。您正在编写API吗?请分享您从数据库获取记录的方法,例如:
User::where('active',1)->get()提供给我,完整的查询/方法,你共享的结果,我要求query@Qazi公共函数getTotalRecord(){return$this->hasOne('App\Post')->selectRaw('store_id,count(*)as counts')->where('status',1)->groupBy('store_id');}尝试获取非objectI am的属性时出现错误,请使用此属性,但不使用打印计数value@AnkitVirani您使用的具体解决方案是什么?如果是第一个,请发布
{{dd($demo->get_total_record)}
我使用了这两种解决方案的结果。