0

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 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I found a simple solution. look here: <img src="{{ image('path/to/image.jpg') }}">. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.