見出し画像

【Laravel 7.x】Laravelで画像投稿機能を実装

前置き

この記事は
・Userテーブルが存在していること
・簡単な投稿機能が書けている
・UserとReport(Postとしている人は随時書き換えて下さい)が1対多の関係である
ということを前提としています。

カラムの追加

$ php artisan make:migration add_image_file_to_reports_table --table=reports

上記のコマンドを実行したら、下記の名前のファイルが生成されるので、そのマイグレーションファイルを編集。

database/migrations/2020_07_18_014619_add_image_file_to_reports_table.php
<上部分は省略>
class AddImageFileToReportsTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::table('reports', function (Blueprint $table) {
           //
           $table->string('image_file')->nullable()->after('body'); //追加
       });
   }
   /**
    * Reverse the migrations.
    *
    * @return void
    */
   public function down()
   {
       Schema::table('reports', function (Blueprint $table) {
           //
           $table->dropColumn('image_file'); //追加
       });
   }
}

追加したら保存してmigrate

php artisan migrate

画像を保存するファイルを作成する

Laravelにはフォルダを生成してくれるコマンドがあるので、まずそれを打ちます。

php artisan storage:link

僕はこちらを参考にして理解しました。
上記のコマンドを実行すると、下の2つのフォルダが生成される。

app/public/storage
app/storage/app/public

Viewを編集

create.blade.php  // 僕このファイルを編集しました。
                <form class="report" method="POST" action="{{ route('report.store') }}" enctype="multipart/form-data">
               @csrf
           --省略---
                   <p>資料(任意)</p>
                   <input class="" name="image_file" type="file" value="{{ old('image_file') }}"><br>
                   <br>

                   <input type="submit" class="btn btn-primary" value="登録する">
               </form>

Controllerを編集

ReportController.php
---省略---
   public function store(StoreReport $request)
   {
       $report = new Report;
       $report->date = $request->input('date');
       $report->body = $request->input('body');
       $report->notice = $request->input('notice');
       $filename = $request->file('image_file')->store('public'); // publicフォルダに保存
       $report->image_file = str_replace('public/','',$filename); // 保存するファイル名からpublicを除外
       $report->user_id = auth()->id();
       $report->save();
       return redirect('report/index');
   }

表示のためにshow functionも編集

ReportController.php

   public function show($id)
   {
       $report = Report::find($id);
       $this->authorize('view', $report); // 認可の記述 今は関係ありません
       return view('report.show', compact('report'));
   }

投稿した画像を表示させる

show.blade.php
<h3 class="show-title">レポート詳細</h3>

               <div class="card report-card">
           --省略--

                   <div class="card-header">
                       <h5>資料</h5>
                   </div>
                   <div class="card-body">
                       <blockquote class="blockquote mb-0">
                       <p><img src="{{ asset('/storage/'.$report->image_file)}}"></p>
                       </blockquote>
                   </div>
               </div>

お終い!

この記事が気に入ったらサポートをしてみませんか?