[Laravel] DBでの配列の使い方(動的に増えるフォーム)
解決したいこと
Laravel6においてレシピアプリを開発中です。
フォームは動的に増え、1つのレシピ(recipes)に対して何個でも材料(materials)を登録できるようにしたいです。
ご教授お願いいたします。
該当するソースコード
RecipeController.php
public function store(RecipeRequest $request)
{
$recipe = Recipe::create(
[
'user_id' => auth()->id(),
'name' => $request->name,
'category_id' => $request->category_id,
'image' => $path,
'process' => $request->process,
]);
$recipe->materials()->createMany([
[
'name' => $request->input('material_name.*'),
'recipe_id' => $recipe->id,
'amount' => $request->input('amount.*'),
'unit' => $request->input('unit.*'),
],
]);
create.php
<div class="form-group">
<label>材料
<input class="form-control" type="hidden" name="recipe_id" value="">
<div class="materials">
<input class="form-control" type="name" name="material_name[]" placeholder="材料名">
<input class="form-control" name="amount[]" placeholder="分量">
<select class="form-control" name="unit[]">
@foreach($units as $unit)
<option value="{{ $unit->name }}">{{ $unit->name }}</option>
@endforeach
</select>
<input type="button" value="+" class="add pluralBtn">
<input type="button" value="-" class="del pluralBtn">
</div>
</label>
</div>
Material.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Material extends Model
{
protected $fillable = [
'name','recipe_id','amount','unit',
];
public function recipe()
{
return $this->belongsTo('App/Recipe');
}
public function unit()
{
return $this->hasOne('App/Unit');
}
}
materials.table.php
public function up()
{
Schema::create('materials', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('recipe_id');
$table->string('name');
$table->string('amount');
$table->string('unit');
$table->timestamps();
$table->foreign('recipe_id')->references('id')->on('recipes')->onDelete('cascade');
});
}
0