douya2007 2016-04-10 22:22
浏览 12
已采纳

限制1张照片显示许多 - Laravel 5.2

How would I display one photo for a product, if there are many photos associated with the product. For example, I just need to display 1 photo in the front page, and i don't want to do a carousel. Here is what I have so far:

My Product Images

As you can see, im doing a for-each loop, and it is displaying all images associated with that product, I only want to display one image.

Here is how I'm displaying the images:

@foreach($products->photos as $photo)                   
    <img src="/store/{{ $photo->thumbnail_path }}">
@endforeach

My Controller to display the Product for this page:

class ProductsController extends Controller {


    /**
     * Show all products
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showProducts() {
        // Get all products
        $product = Product::all();

        return view('admin.product.show', compact('product'));
    }

}

My Product Model (shortened):

    class Product extends Model {

    /**
     * One Product can have many photos.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function photos() {
        return $this->hasMany('App\ProductPhoto');
    }

}

And this is how my Products Images Tables look like:

My Images Table

My Products Table

  • 写回答

1条回答 默认 最新

  • drgm51600 2016-04-10 22:27
    关注

    Ditch the @foreach and use first() on the photos collection:

    <img src="/store/{{ $products->photos->first()->thumbnail_path }}">
    

    If you want to be able to choose which one's featured, you could add a boolean featured column to the photos table and do something like this:

    public function featuredPhoto() {
        return $this->hasOne('App\ProductPhoto')->whereFeatured(true);
    }
    

    and:

    <img src="/store/{{ $products->featuredPhoto->thumbnail_path }}">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案