Laravel直接访问刀片中的json数组,而不使用foreach语句

时间:2017-12-08 12:49:06

标签: php laravel laravel-5

在这个结果中:

LengthAwarePaginator {#251 ▼
  #total: 2
  #lastPage: 1
  #items: Collection {#246 ▼
    #items: array:2 [▼
      0 => ProductCategories {#247 ▼
        ...
        #attributes: array:6 [▼
          "id" => 1
          "category_name" => "test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        #original: array:6 [▼
          "id" => 1
          "category_name" => "test test"
          "lang" => "fa"
          "images" => "{"images":{"original":"\/uploads\/post_images\/2017\/1512736029.jpeg","300":"\/uploads\/post_images\/2017\/300_1512736029.jpeg","600":"\/uploads\/post_images\/2017\/600_1512736029.jpeg","900":"\/uploads\/post_images\/2017\/900_1512736029.jpeg"},"thumbnail":"\/uploads\/post_images\/2017\/300_1512736029.jpeg"} ◀"
          "created_at" => "2017-12-08 10:47:56"
          "updated_at" => "2017-12-08 12:27:10"
        ]
        ...
      }
      1 => ProductCategories {#248 ▶}
    ]
  }

我从这个查询得到:

$categories = ProductCategories::paginate(10);
dd($categories);

我正在尝试访问"images"列数据,例如thumbnail300等,当我使用foreach此数据并在{{1}上显示时我无法访问它们,例如:

table

但我收到{{$categories->images->thumbnail}} 错误,我无法显示

3 个答案:

答案 0 :(得分:1)

你只是强制该字段到数组......

class ProductCategories ...
{
    protected $casts = [
        'images' => 'array',
    ];

    ...
 }


 @foreach ($categories as $category)
     {{ $category->images['thumb'] }}
 @endforeach

Laravel 5.5 Docs - Eloquent - Mutators - Array and Json Casting

答案 1 :(得分:0)

变量@foreach($categories as $category) {{ $category->images }} @endforeach 是一个集合,因此您需要让每个单独的对象获取其数据。为此,你需要使用foreach。

thumbnail

要访问images,您需要解码json_decode($category->images)中的json字符串。为此,您可以使用thumbnail功能。这将返回一个以{{1}}为键的数组。

答案 2 :(得分:0)

如果你想做对,你应该将图像相关数据保存在一个单独的表中,并使用类别和图像之间的关系:

public function images()
{
    return $this->hasMany(Image::class);
}

但是,由于您将图像数据保存为JSON字符串,因此您要做的第一件事就是cast it to array。将其添加到模型中:

protected $casts = [
    'images' => 'array',
];

然后在Blade视图中:

@foreach ($categories as $category)
    {{ $category->images['thumbnail'] }}
@endforeach