1
0

More than 3 years have passed since last update.

laravel8に画像をアップロードするやり方②

Last updated at Posted at 2021-05-20

前回の概要

Untitled Diagram.png

今回行いたいこと

  • 画像をデータベースに保存する

データベースに保存する

Controller フォルダ内にある UserController.php 内の内容を変更する。今回は、Eloquentメソッドの fill を使ってデータベースに保存しました。

UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Image;


class UserController extends Controller
{

    public function edit2(Request $request)
    {
        return view('edit');
    }


    public function update(Request $request)
    {   
        // 画像のアップロード
        $path = $request->file('image')->store('public/avatar');
        $image_path = basename($path);

        // // DBにアップロードする
        $image_path2 = new Image();
        $image_path2->fill([
            'user_id'=>1,
            'image_name'=>'',   
            'image_path'=>$image_path,
            ]);
        $array_2=(array)$image_path2;
        $image_path2->fill($array_2)->save();    


        return redirect("/users/edit")->with("message", "アップロードに成功しました。");
        // $image_path2->image_pass = $image_path;
        // $image_path2->save();
    }
}
UserController.php
$array_2=(array)$image_path2;
$image_path2->fill($array_2)->save();    

上のコードの一行目で、 image_path2 を型変換して配列に変えています。その後、fill に入れています。

ちなみに今回のテーブルの構成は下のようになっています。

Image.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    // use SoftDeletes;
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];
    protected $fillable = [
        'user_id',
        'image_name',
        'image_path',
    ];
    public function user()
    {
        return $this->belongsTo(user::class);
    }
}

今回のまとめ

Untitled Diagram (1).png

次回に向けて

まだシンプルな中身なので、次はコメント履歴とコメントを作成したいと思います。
もしよろしければ、フォローお願いします!!!!!

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