如何在Laravel 5.6的索引页面中仅显示一张图像? [英] How to show only one image in the index page in Laravel 5.6?
问题描述
我的桌子上有多个与 vehicle_id
相关的图像,
I have multiple images in my table witch related to vehicle_id
, like this,
image table
id fileName vehicle_id
1 1.jpg 1
2 2.jpg 1
3 3.jpg 1
4 4.jpg 1
5 28.png 2
5 28.png 2
6 29.png 2
7 30.png 3
8 31.png 3
9 56.png 3
使用 VehicleController
$vehicles = Vehicle::with('image')->get();
return view('vechicles.index')->withVehicles($vehicles);
现在这些图像显示在Vehicles/index.blade.php文件中
Now these images are showing in the vehicles/index.blade.php file
@foreach($vehicle->images as $image)
<tr>
<td><a href="{{route('vechicles.show',$vehicle->id)}}"><img src="/images/{{ $image->resized_name }}"></a></td>
</tr>
@endforeach
我的问题现在发生了,这样,我可以显示表中与正确vehicle_id
相关的所有图像,但是,我只需要显示一张图像(匹配vehicle_id
代码>),就像缩略图一样位于上方.那我该如何配置呢?
My problem is occurred now, in this way, I can show all images in the table which related to proper vehicle_id
but, I need only show one image (to matching vehicle_id
) like thumbnail to above line.
Then how can I configure this?
更新的控制器
public function index()
{
$vehicles = Vehicle::with('images')->get();
return view('vechicles.index')->withVehicles($vehicles);
}
更新了完整刀片
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@if($vehicles)
@foreach($vehicles as $vehicle)
{{$vehicle->district}}
{{$vehicle->town}}
{{$vehicle->brand}}
{{$vehicle->model}}
<hr>
@foreach($vehicle->images as $image)
<tr>
<td><a href="{{route('vechicles.show',$vehicle->id)}}"><img src="/images/{{ $image->resized_name }}"></a></td>
</tr>
@endforeach
@endforeach
@endif
</div>
</div>
</div>
@endsection
推荐答案
您正在循环浏览所有图像.您只需使用以下代码即可检索图像:
You are looping through every images right now. You can simply retrieve an image using code below:
$vehicle->images()->first()->resized_name
因此,用于显示图片的代码将是:
So your code to display image will be:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@if($vehicles)
@foreach($vehicles as $vehicle)
{{$vehicle->district}}
{{$vehicle->town}}
{{$vehicle->brand}}
{{$vehicle->model}}
<hr>
<tr>
<td>
<a href="{{route('vechicles.show',$vehicle->id)}}"><img
src="/images/{{ $vehicle->images()->first()->resized_name
}}"></a>
</td>
</tr>
@endforeach
@endif
</div>
</div>
</div>
@endsection
这篇关于如何在Laravel 5.6的索引页面中仅显示一张图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!