LoginSignup
1
4

More than 3 years have passed since last update.

Laravelで画像パスをDBに保存して表示する方法!

Posted at

今回はLaravelで画像保存するやり方をまとめていくぅ!!

作業フロー

初動
・migration 作成
・model 作成
・controller 作成
・viewファイル作成
①DBに画像パス保存のカラム作成(migration)
②モデルの編集
③ルーティング
④シンボルリンクのやつ(php artisan storage:link)
⑤コントローラー編集
⑥viewに画像投稿フォーム作成
⑦表示処理

初動

migrationとmodelを同時に生成!

php artisan make:model -m Image 

controller作成

php artisan make:controller  ImageController

viewファイル作成

ディレクトリー構成
resources/views/image/○○○○blade.php

作成ファイル
index.blade.php
form.blade.php


①DBに画像パス保存のカラム作成(migration)

    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('image');←追記
            $table->timestamps();
        });
    }

普通にmigrationしていく!
型はstring(パスは文字列だから?)

②モデルの編集

class Image extends Model
{
        protected $fillable = [

        'image',

        ];
}

$fillableにimageカラムを指定

③ルーティング

Route::get('/images', 'ImageController@index');画像表示ページ
Route::get('/image/form', 'ImageController@form');画像投稿フォーム
Route::post('/image/store', 'ImageController@store');画像保存

画像表示ページ、画像投稿フォーム、画像保存のためのルーティングを記述

④シンボルリンクのやつ(php artisan storage:link)

php artisan storage:link

コンソールで入力
参考 https://readouble.com/laravel/7.x/ja/filesystem.html

⑤コントローラー編集

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image ←追記

class ImageController extends Controller

{
    public function index()
    {
     $images = Image::all();//レコード取得
     return view('image.index',compact('images')); //一覧ページ表示
     }

    public function form()
    {
    return view('image.form')//投稿フォーム表示
    }

//保存処理がちょい複雑かもぉ(o_o)「
    public function store()
    {
        //画像の処理
        $image = $request->file('image');//file()で受け取る
        if($request->hasFile('image') && $image->isValid()){//画像があるないで条件分岐
            $image = $image->getClientOriginalName();//storeAsで指定する画像名を作成
        }else{
            return;

    Image::create([
      'image' => $request->file('image')->storeAs('public/images',$image),
     ]);
//storage/app/public/images(imagesは作られる)に保存

    return redirect(/images);//保存処理後一覧ページに飛ばす

    }


⑥viewに画像投稿フォーム作成

form.blade.php

 <form action="/image/store" method="post" enctype="multipart/form-data">
 @csrf
 <input type="file" name="image" accept="image/png, image/jpeg">
 <input type="submit" value="投稿"> 
 </form>

formタグに enctype="multipart/form-data" を入れる!

⑦表示処理
index.blade.php

@foreach($images as $ image)

<img src"{{ Storage::url($image->image) }}">

@endforeach

foreachで回して画像を一枚づつ表示

終わり

作業フローにしてまとめてみました!
なぞるだけでできたでしょうか?
もしできたら、これ何って思ったものはググってください!

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