You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Blade中如何从图片数组仅显示第一张图片?

仅显示图片数组的第一张图片

有两种简单的实现方式:

方法一:直接获取数组首元素(推荐)

先将图片字符串分割为数组,直接取第一个元素,无需循环:

@php
    $imageArray = explode('|', $product->images);
    $firstImage = $imageArray[0] ?? '';
@endphp
@if($firstImage)
    <img style="width:100%" src="/storage/image/{{$firstImage}}">
@endif

这里用?? ''做空值处理,避免当$product->images为空时出现数组索引错误,同时通过@if判断确保只有存在图片时才渲染标签。

方法二:循环中只渲染第一个元素

保留循环结构,但仅处理第一个元素后终止循环:

@foreach (explode('|', $product->images) as $index => $image)
    @if($index === 0)
        <img style="width:100%" src="/storage/image/{{$image}}">
        @break
    @endif
@endforeach

通过$index判断是否为第一个元素,渲染后用@break跳出循环,避免多余的循环执行。

内容的提问来源于stack exchange,提问作者Abrar Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:53:16