I’ve been trying to use an if statement in my view which basically checks if the images in the carousel are null, however my if statement doesn’t seem to be working and I’m getting Trying to get property ‘images’ of non-object I’m not sure why it’s not returning the placeholder image. Is there something I’m doing wrong? Thank you.
View
<div id="carouselExampleCaption" class="carousel slide" data-ride="carousel"> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> @if($firstImage->images != null) <img src="{{ Storage::url("image/{$firstImage->images}") ?? '' }}" alt="..." class="d-block img-fluid"> @elseif($firstImage->images == null) <img src="https://via.placeholder.com/1400x800.png?text=Awaiting+images" alt="..." class="d-block img-fluid"> @endif </div> @if($vehicleImages != null) @foreach($vehicleImages as $images) <div class="carousel-item"> <img src="{{ Storage::url("image/{$images->images}") ?? '' }}" alt="..." class="d-block img-fluid"> </div> @endforeach @elseif($vehicleImages == null) <img src="https://via.placeholder.com/1400x800.png?text=Awaiting+images" alt="..." class="d-block img-fluid"> @endif </div> <a style="opacity: unset;" class="carousel-control-prev" href="#carouselExampleCaption" role="button" data-slide="prev"> <span aria-hidden="true"><i style="font-size: 40px;" class="fas fa-chevron-left"></i></span> <span class="sr-only">Previous</span> </a> <a style="opacity: unset;" class="carousel-control-next" href="#carouselExampleCaption" role="button" data-slide="next"> <span aria-hidden="true"><i style="font-size: 40px; color: white;" class="fas fa-chevron-right"></i></span> <span class="sr-only">Next</span> </a> </div>
Controller
public function show(Request $request) { $post = Post::where('vehicle', $request->vehicle)->first(); $posts = Post::all()->sortByDesc('created_at')->take(3); $image = Images::get(); $firstImage = $image->where('post_id', $post->id)->sortBy('id')->first(); $vehicleImages = $image->where('post_id', $post->id); return view('Frontend::pages.press.show', compact('post', 'posts', 'firstImage', 'vehicleImages')); }
Advertisement
Answer
<div class="carousel-item active"> @if($firstImage != null) <img src="{{ Storage::url("image/{$firstImage->images}") ?? '' }}" alt="..." class="d-block img-fluid"> @elseif($firstImage == null) <img src="https://via.placeholder.com/1400x800.png?text=Awaiting+images" alt="..." class="d-block img-fluid"> @endif </div>