I try to print an image uploaded by user in Laravel 5.4. I use an if condition and if user does not upload any image, then default image is displayed but my source code somehow prints nothing. This the code I use:
@if (File::exists($post->image))
{
echo "<img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" />";
} else {
echo "<img src="{{ asset('images/no-image.png') }}" alt="{{ $post->title }}" />";
}
@endif
Update:
I try to use this code:
@if (File::exists(public_path("asset/uploads/".$post->image)))
<img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" />
@else
<img src="{{ asset('images/no-image.png') }}" alt="{{ $post->title }}" />
@endif
And the result now I'm getting:
if i use asset/uploads Or assets/uploads in if all images return to no-image even if they have image.
if I use uploads if if posts with image shows but other shows no image and the url i'll get for them is url.dev/uploads instead of url.dev/images/no-image.png .
File::exists() will check the physical location of file in hard disk. So you must use actual path to the file.
@if (File::exists(public_path("assets/uploads/".$post->image)))
<img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" />
@else
<img src="{{ asset('images/no-image.png') }}" alt="{{ $post->title }}" />
@endif
Cross check the path generated by `public_path' method is correct to your file.
Update: thanks to linktoahref, turns out your blade code is also wrong. Corrected here.
File::exists works same as php's file_exists which will return true even if you search for directory, now what happens here that for some posts image is null which make path a directory.
Use this code instead.
@if ($post->image && File::exists(public_path("uploads/".$post->image)))
<img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" />
@else
<img src="{{ asset('images/no-image.png') }}" alt="{{ $post->title }}" />
@endif
You are mixing raw php and blade templating together, either stick with raw php code or blade templating syntax
So it would be the following in blade
@if (File::exists($post->image))
<img src="{{ asset('uploads/' . $post->image) }}" alt="{{ $post->title }}" />
@else
<img src="{{ asset('images/no-image.png') }}" alt="{{ $post->title }}" />
@endif
Or use raw php as
<?php
if (File::exists($post->image)) {
echo "<img src=". asset('uploads/' . $post->image) . " alt=" . $post->title . " />";
} else {
echo "<img src=". asset('images/no-image.png') . " alt=". $post->title ." />";
}
?>