前回の概要
今回行いたいこと
- 画像をデータベースに保存する
データベースに保存する
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);
}
}
今回のまとめ
次回に向けて
まだシンプルな中身なので、次はコメント履歴とコメントを作成したいと思います。
もしよろしければ、フォローお願いします!!!!!