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

Laravelで画像アップロードする方法

Posted at

画像アップロード

【Laravel】storageに画像を保存してpublicに表示する方法(初心者向け)

🔸 記事構成案

はじめに

対象読者(Laravel初心者、画像アップロード実装中の方)

▼本記事でできること

  • 画像ファイルのアップロード

  • storageディレクトリへの保存

  • publicに表示する方法

前提環境

  • Laravelバージョン

  • 使用するBlade/コントローラー/ルートの構成

  • .env設定例(ファイルサイズ上限やAPP_URLなど)

フォームの作成(Blade)

<form action="{{ route('profile.update') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="profile_image" required>
    <button type="submit">アップロード</button>
</form>

コントローラー処理

public function update(ProfileRequest $request)
{
    if ($request->hasFile('profile_image')) {
        $filename = $request->file('profile_image')->store('profile_images', 'public');
        $user = auth()->user();
        $user->profile->profile_image = $filename;
        $user->profile->save();
    }

    return redirect()->route('profile.show')->with('success', '画像をアップロードしました');
}

画像の表示

<img src="{{ asset('storage/' . $user->profile->profile_image) }}" alt="プロフィール画像">

storage:link の注意点

php artisan storage:link

※public/storage → storage/app/public のシンボリックリンクが必要

バリデーション(ProfileRequest例)

public function rules()
{
    return [
        'profile_image' => 'nullable|image|max:2048',
    ];
}
1
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
1
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?