lundi 9 mai 2016

How to display values inside pivot table using eloquent in laravel

I have this enrollment project, that a student will only choose the subjects he/she wants to enroll. Those subject will be fetch automatically and be displayed on a table. See this image. After the student will click on the add button of the enrollment form, the subject will be added to the added subjects form. However I am having problem displaying the values of all sections and subjects define on my pivot table which is the section_subject. How can I achieve this? I already define belongsToMany relationships on the Section Model and Subject Model. Here's my code.

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 as $subject)
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></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 the 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 are the subjects table and 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();
});



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire