Can laravel built-in html elements be overridden? for example, consider HTML:image tag. I am wondering if I can override it in order to show 'no_available_image.svg' when the given image path doesn't exist.
1 Answers
You can't override an <img>
tag (or you shouldn't), but there are other ways to achieve an image fallback.
Also, take in account that HTML:image tag is not a Laravel built-in element, is just HTML and Laravel has nothing to do here.
Blade PHP solution
Check that file exists. If not, it will echo
the fallback image.
@if (file_exists(public_path('path/to/image.jpg')))
<img src="{{ asset('path/to/image.jpg') }}">
@else
<img src="{{ asset('images/no_available_image.svg') }}">
@endif
Vue + Blade solution
Following this question, you can create a Vue component like this:
ImgFallback.vue
<template>
<object :data="src" type="image/png">
<img :src="fallback" />
</object>
</template>
<script>
export default {
props: {
src: String,
fallback: String
}
}
</script>
then register it in your app.js
Vue.component('img-fallback', require('./components/ImgFallback.vue'));
So then in your blade templates you can use:
<img-fallback
src="{{ asset('wrong_image_path') }}"
fallback="{{ asset('images/no_available_image.svg') }}">
</img-fallback>
Reusing code
Since you will be using blade and the same fallback image in all cases, you don't want to repeat the fallback attribute everytime, so you can create a blade template called for example image.blade.php
and put in the javascript or PHP option. Then in your views call:
@include('image', [ 'path' => 'path/to/your/image.jpg' ])
And use the $path
variable to fill the src
attribute in the image.blade.php
file.
@if (file_exists(public_path($path)))
<img src="{{ asset($path) }}">
@else
<img src="{{ asset('images/no_available_image.svg') }}">
@endif
or
<img-fallback
src="{{ asset($src) }}"
fallback="{{ asset('images/no_available_image.svg') }}">
</img-fallback>

- 1
- 1

- 3,048
- 3
- 28
- 39
-
I found a simple solution. look here:
. while image is a helper method which check if the path exists return asset($path) otherwise it returns $path('no_available_image.svg'); it works! simple and stupid. – Mostafa Apr 23 '17 at 06:45