ErikRobles's avatar

How can I display an icon depending on file type in the view?

Hello and thank you for taking the time to help me with my question. I have a task application which is working great. When you upload images, you can see their thumbnails and even click on them and be directed to a new tab to view the images at 100%. The problem is that when a client uploads a pdf, the icon shows up as a broken image icon. This makes sense as the img tag within the a tag obviously is an image icon.

My question is how can I indicate in my show.blade.php that it is an image when it is an image and a pdf or dox when it is a pdf or doc? Like I said, the app is working so the only code I am concerned with is the following (unless I am mistaken, please let me know):

...
<a data-toggle="" href="/storage/upload/{{ $images[$i]['name'] }}" target="_blank">
    <img src="/storage/upload/{{ $images[$i]['name'] }}" class="image-fluid w-50">
 </a>

               </div>
               @endfor
               @else
               <p class="ml-3 mb-1">No files found</p>
               @endif

           </div>

I am looking for something like: If file type is img (of any type) display the image thumb, if not, display an icon that represents "file".

Any help on this would be greatly appreciated. Thank you in advance.

0 likes
4 replies
ErikRobles's avatar

Hello jlrdw and thank you for the response. In my case, how would that translate into an conditional. I assume this can be done within the code I have presented but I am unclear to go about it. Would I use an @if? Even though my variable is set to $image, I have allowed for any file type between img, png, pdf, docx etc.

MichalOravec's avatar
Level 75

Check an extension and if it's an image just show it, othewise show icon of extension for exampe /icons/pdf.jpg for pdf

@if (in_array($extension = pathinfo($images[$i]['name'], PATHINFO_EXTENSION), ['jpg', 'png', 'bmp']))
    <a data-toggle="" href="/storage/upload/{{ $images[$i]['name'] }}" target="_blank">
        <img src="/storage/upload/{{ $images[$i]['name'] }}" class="image-fluid w-50">
    </a>
@else
    <img src="{{ "/icons/{$extension}.jpg" }}" class="image-fluid w-50">
@endif
1 like
ErikRobles's avatar

Great @MichalOravec. I only had to add the icons folder with the images, and give the else an a tag to the file and boom. Worked like a charm. Thank you.

Please or to participate in this conversation.