How to display values inside pivot table using eloquent in laravel -
i have enrollment project, student choose subjects he/she wants enroll. subject fetch automatically , displayed on table. see image. after student click on add button of enrollment form, subject added added subjects form. having problem displaying values of sections , subjects define on pivot table section_subject. how can achieve this? define belongstomany relationships on section model , subject model. here's code.
subject.php
class subject extends model { public function sections() { return $this->belongstomany(section::class); } }
section.php
class section extends model { public function subjects() { return $this->belongstomany(subject::class); } }
reservationcontroller class
class reservationcontroller extends controller { public function create($id) { $subjects = subject::with('sections')->get(); return view('reservation.form',compact('subjects')); } }
form.blade.php
<tr> <th>section</th> <th>subject code</th> <th>descriptive title</th> <th>schedule</th> <th>no. of units</th> <th>room</th> <th>action</th> </tr> <body> @foreach($subjects $subject) <tr> <td>{{ $subject->section_code }}</td> <td>{{ $subject->subject_code }}</td> <td></td> <td></td> <td>{{ $subject->units }}</td> <td>df</td> <td> <button class="btn btn-xs btn-primary">add</button> <button class="btn btn-xs btn-info">edit</button> </td> </tr> @endforeach
here's section_subject table
schema::create('section_subject', function (blueprint $table) { $table->integer('section_id')->unsigned(); $table->integer('subject_id')->unsigned(); $table->foreign('section_id') ->references('id') ->on('sections') ->ondelete('cascade'); $table->foreign('subject_id') ->references('id') ->on('subjects') ->ondelete('cascade'); $table->primary(['section_id', 'subject_id']); });
also, here subjects table , section table respectively.
schema::create('subjects', function (blueprint $table) { $table->increments('id'); $table->integer('department_id')->unsigned(); $table->string('subject_code'); $table->string('subject_description'); $table->integer('units'); $table->integer('cost'); $table->timestamps(); }); schema::create('sections', function (blueprint $table) { $table->increments('id'); $table->integer('instructor_id')->unsigned(); $table->string('section_code'); $table->string('section_description'); $table->string('room_no'); $table->date('schedule'); $table->date('semester'); $table->timestamps(); });
try {{ $subject->pivot->section_code }}
also, add relation:
->withpivot('section_code')
more on getting data pivot tables here.
Comments
Post a Comment