0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ファイルの拡張子に応じてアイコンを変更する方法

Last updated at Posted at 2025-05-07

はじめに

本記事では、ファイルの拡張子に基づいて、PDFファイルにはPDFアイコン(PDF.png)を、それ以外のファイルにはデフォルトアイコン(image.png)を表示する方法を解説します。

事前準備

アイコン画像を用意する必要があります。以下のファイルを public/resource/images/ フォルダ に保存してください。

  • PDF.png : PDFファイル用アイコン

  • image.png : その他のファイル用アイコン

この例では、アイコン画像をpublic/resource/images/ディレクトリ内に配置する前提で進めます。

コントローラーで $attachment_icon をビューに渡す

コントローラーの変更
コントローラー内で、ファイルの拡張子をチェックし、その結果をビューに渡します。

MessageController.php
public function show(talk_message $message)
{
    // ファイルの拡張子を取得
    $attachments_file_extension = pathinfo($message->attachments_file, PATHINFO_EXTENSION);
    
    // ファイルのアイコン設定
    $attachment_icon = ($attachments_file_extension == 'pdf') ? 'resource/images/PDF.png' : 'resource/images/image.png';

    // ビューにアイコンを渡す
    return view('show', compact('message', 'attachment_icon'));
}

ビューでの使用
コントローラーで渡された $attachment_icon をビューでそのまま使用します。

blade.php
<img src="{{ asset($attachment_icon) }}" alt="Attachment Icon">
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?