Michael Kročka
Michael Kročka

Reputation: 655

Displaying an image in blade.php file

I am making a laravel application to serve as a backend to my website. I have an image (images) stored in a postgresql database. The format is bytea. I now want to display this image but it is showing me an error message.

Facade\Ignition\Exceptions\ViewException htmlspecialchars() expects parameter 1 to be string, resource given (View: C:\wamp64\www\WebTech\resources\views\shop\index-temp.blade.php)

I can't figure out whats wrong. Here is the code that is producing this error.

    @foreach($productsList as $product)
    <div class="col text-center">
       <a href="/products/{{$product->id}}">
          <img class="img-fluid" srcset="{{ $product->image_200 }} 200w, {{ $product->image_300 }} 300w"
                                 sizes="(max-width: 480px) 200px, 300px" 
                                 src="{{ $product->image_300 }}" alt="{{ $product->alt_text }}">
          <p class="mb-0 text-center text-white">{{ $product->name }}<br>{{ $product->cost }} eur</p>
          <p>{{$product->image_200}}</p>
      </a>
   </div>
   @endforeach

For clarification, the columns image_200, image_300 and image_500 are in bytea format in postgresql database. I have tried using the pg_unescape_bytea({{ $product->image_300 }}) function, but it doesn't help. What is the correct way to display an image in this way?

Upvotes: 1

Views: 496

Answers (1)

lagbox
lagbox

Reputation: 50481

As per https://stackoverflow.com/a/33499238/2109233 :

Try to get the stream contents, then unescape the bytea:

{{ pg_unescape_bytea(stream_get_contents($product->image_300)) }}

I am not sure what format that will end up in, if it can't go through htmlspeciachars replace {{ }} with {!! !!}.

You could move this into an accessor so you can just call $product->image_300 and have it converted for you.

You probably want to be using a data URI scheme for the image src attribute.

Update:

Apparently you may not need the pg_unescape_bytea function but you do need to use a Data URI scheme for the image source.

Upvotes: 1

Related Questions