Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lipa's avatar
Level 1

Display file icon in view depending on file extension

What is the best way to display an icon of file, based on extension?

                            @foreach($user->files as $file)
                            <tr>
                                <td>{!! $file->extension !!}</td>
                                <td>{!! $file->name !!}</td>
                                <td>{!! $file->created_at !!}</td>
                                <td>{!! $user->name !!}</td>
                                <td>
                                    <a href="{!! route('files.download', [$user->id, $file->id]) !!}" class="btn btn-xs btn-success">Pobierz</a>
                                    <a href="{!! route('files.destroy', [$user->id, $file->id]) !!}" class="btn btn-xs btn-danger">Usuń</a>                             
                                </td>                           
                            </tr>
                            @endforeach     

What is a good way to display an icon? I supposted to use few if statements or there is better way to do this?

@if ($file->name === 'png' or $file->name === 'jpg' or $file->name === 'gif' )
    <img src="image.png">
@if ($file->name === 'pdf' )
    <img src="pdfdocument.png">
...
0 likes
3 replies
skliche's avatar

@lipa Implement a method on your file model that determines the appropriate image so your view stays clean:

{{ $file->icon() }}

That method would return a string like image.png or pdfdocument.png.

1 like
Snapey's avatar

Building on what @skliche suggested, adding an accessor method in your file model like;

    public function getIconAttribute() {

        $extensions = [
            'jpg' => 'jpeg.png',
            'png' => 'png.png',
            'pdf' => 'pdfdocument.png',
            'doc' => 'wordicon.jpg',
        ];

        return array_get($extensions,$this->extension,'unknown.png');
    }

The array_get is a laravel helper that looks up a value in an array and can have a third parameter of a default if the extension is not found in the array.

Then in blade you can just <img src='/images/{{$file->icon}}' />

1 like
Snapey's avatar

Or, a simpler approach where you just make sure to name the icon the same as the extension.

Then in blade you can just <img src='/images/{{$file->extension}}.png' /> and then you don't need to add the accessor at all.

It does not though allow for unknown file types but this might be ok if you are restricting the types of upload (which you should).

Please or to participate in this conversation.