画像をアップロードしてその情報をデータベースに書き込むことはできたのですが、そのデータベースに他の情報もいろいろと記録したいと思います。
というよりも、作りたいのは画像も保存できるテキスト主体のカード型データベースです。
現在、django で動いているアプリは本当に重宝しているので、それを laravel で実現したいのです。
画像は必ずしも必要ではないという設定にします。
migration table
comment を追加。
database/migrations/******_create_images_table
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->text('comment') -> nullable(true);
$table->string('img_path') -> nullable(true);
$table->timestamps();
});
}
imgdb のすべてのテーブルを削除してから migration。
php artisan migrate
model の編集
app/Models/Image.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $table = 'images';
protected $fillable = [
'category',
'comment',
'img_path',
];
}
controller の編集
app/Http/Controllers/ImageController.php
public function store(Request $request)
{
$img = $request->file('img_path');
if (isset($img))
{
$path = $img->store('img','public');
}
else
{
$path = null;
}
Image::create([
'category' => $request->category,
'comment' => $request->comment,
'img_path' => $path,
]);
return redirect()->route('item.index');
}
view の変更
resources/views/item/index.blade.php
<form action="{{ route('item.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="text" name="comment">
<input type="file" name="img_path">
<input type="submit" value="アップロード">
</form>
変数の渡し方
form で、
<input type="text" name="comment">
として送り、controller で、
public function store(Request $request)
Image::create([
'comment' => $request->comment,
]);
で受けます。
一番わかりにくいのが、「Image::create」。
おそらく、Image モデルを呼び出してデータを記録しているんでしょう。
なので、Image.php も対応して変更しておく必要があります。