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
The vehicle table have way to many relationship with the image table and data grap using eager loader in VehicleController
$vehicles = Vehicle::with('image')->get();
return view('vechicles.index')->withVehicles($vehicles);
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
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?
updated Controller
public function index()
{
$vehicles = Vehicle::with('images')->get();
return view('vechicles.index')->withVehicles($vehicles);
}
updated full blade
@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 just have to dispaly the first array image in the blade as shown below:
You can simply take only the first image. But be aware that you must verify if there are any images for that vehicle otherwise an exception will be thrown.
You are looping through every images right now. You can simply retrieve an image using code below:
So your code to display image will be:
You can use laravel
first()
function.You can use limit along with
with
function like:And write code to show image as: