LoginSignup
0
1

More than 3 years have passed since last update.

PHP Laravel 6 画像のアップロード

Last updated at Posted at 2020-09-27

前提条件

画像ファイルの保存先 = storage/app/public
データベースにはファイル名のみを保存。
ファイル名にはランダムな名前が自動で割り当てられる。

フォームの作成

フォームタグの記述

formタグに enctype='multipart/form-data' を記述しないとエラーを吐きます。
これを記述することで複数類(jpeg、png等)のデータ形式を扱う事でできるようになります。

create.blade.php
<form method="POST" action="{{ route('recommends.store') }}" enctype='multipart/form-data'>
@csrf

</form>

コントローラーの設定

imgがない場合に$path = $request->file('img')->store('public/img');でエラーを吐くためif文で分岐させました。

recommendMovies/app/Http/Controllers/RecommendMovieController.php
public function store(Request $request)
    {
      if ($request->img === null) {
        RecommendMovie::create([
          'name' => $request->name,
          'description' => $request->description,
          'impression' => $request->impression,
        ]);
      }else {
        $path = $request->file('img')->store('public/img');
        RecommendMovie::create([
          'name' => $request->name,
          'description' => $request->description,
          'impression' => $request->impression,
          'img' => basename($path)
        ]);
      }
      return redirect('/recommends')->with('message', '作成しました');
    }

viewの設定

シンボリックリンクを使用します。

php artisan storage:link

storage\imgが作成され、この中にアップロードした画像が保存されます。
Screen Shot 2020-09-27 at 12.03.56.png

以下の記述でブラウザに表示させることができます。

recommendMovies/app/Http/Controllers/index.php
<img src="{{ asset('/storage/img/'.$recommend->img) }}">
0
1
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
1