Hello,
I'm working on a project who have one of his features adding new Packs that contains many courses, also courses can have many packs it's mean as I know the ManyToMany relationship so I should work with pivot table.
I have already courses in my Database, I want to add a new pack with courses, It didn't work. I will list below all my current working on code. Thanks in advance for help
Course Model:
public function packs()
{
return $this->belongsToMany(Pack::class);
}
Pack Model:
public function course()
{
return $this->hasMany(Course::class);
}
My Blade:
<form action="{{ route('pack.store') }}" method="POST" enctype="multipart/form-data">
@csrf
@method('POST')
<div class="mb-4">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" required="" placeholder="Name">
</div>
<div class="mb-4">
<label for="course_id">Select Course for this pack <span style="color: red;">*</span></label>
@foreach ($courses as $course)
<div class="form-check">
<input type="checkbox" name="course_id[]" value="{{ $course->id }}" id="course_id">
<label for="course_id">{{ $course->title }}</label>
</div>
@endforeach
</div>
<button class="btn btn-outline-success" type="submit">Create Pack</button>
</form>
PackController:
public function store(StorePackRequest $request)
{
$newPack = new Pack;
$newPack->name = $request->name;
$newPack->courses()->attach($request->course_id);
dd($newPack);
$newPack->save();
return redirect()->route('pack.create')->with('status', ' The pack has been created with selected courses');
}
Pivot table migration:
Schema::create('course_pack', function (Blueprint $table) {
$table->id();
$table->foreignId('course_id')->nullable()->constrained();
$table->foreignId('pack_id')->nullable()->constrained();
$table->timestamps();
});