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?

【5分で復習】 Laravelで「フォーム → ファイルをアップロード → 保存」する手順

Last updated at Posted at 2025-10-29

最終のゴールは他のストレージにファイルを保存する実装を目指すが、まずは簡単なところから復習をする。

1. まずはフォームを作る

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

2. ルーティングを作る(routes/web.php)

Route::post('/upload', [App\Http\Controllers\FileUploadController::class, 'store'])
    ->name('file.upload');

3. コントローラを作成

php artisan make:controller FileUploadController

Dockerを利用しているならdocker composeが必要

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function store(Request $request)
    {
        // バリデーション
        $request->validate([
            'myfile' => 'required|file|max:2048', // 2MBまで
        ]);

        // ファイルの保存
        $path = $request->file('myfile')->store('uploads');

        return back()->with('success', 'アップロード完了!保存先: ' . $path);
    }
}

保存される場所について

プロジェクト/
 └ storage/
    └ app/
       └ uploads/   ← ここに保存

store('uploads') は
storage/app/uploadsフォルダに保存する、という意味。

「ストレージ」と「サーバーの公開ディレクトリ」の違い

場所 役割 URLで直接アクセスできる?
storage/app Laravel内部用のファイル保存場所(非公開領域) できない
public/ Webブラウザからアクセスして良い公開用フォルダ できる

つまりアップロードしたファイルをWebからダウンロードしたい場合はpublic配下にファイルを保存しなければいけない。

これが基本のおさらい。

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?