Home > Software engineering >  How to Display Data from Table relationship base on ID come from first table LARAVEL
How to Display Data from Table relationship base on ID come from first table LARAVEL

Time:12-26

I have 3 table, table Courses, table Sections, and table Syllabuses. Where table courses relation to table Sections and table Sections relation to table Syllabuses. To make clear below my table look like:

#Table Courses:

public function up()
    {
        Schema::create('courses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->unsignedBigInteger('category_id')->default('1');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
            $table->string('title');
            $table->string('status')->default('publish');
            $table->text('content')->nullable();
            $table->string('level');
            $table->date('start_at');
            $table->date('ended_at');
            $table->integer('capacity');
            $table->text('image')->nullable();
            $table->text('url')->nullable();
            $table->text('requirement')->nullable();
            $table->softDeletes();
            $table->timestamps();
        });
    }

Table Sections:

public function up()
    {
        Schema::create('sections', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('course_id');
            $table->foreign('course_id')->references('id')->on('courses');
            $table->string('name');
            $table->timestamps();
        });
    }

and the last table Syllabuses:

public function up()
    {
        Schema::create('syllabuses', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('section_id');
            $table->foreign('section_id')->references('id')->on('sections')->onDelete('cascade')->onUpdate('cascade');
            $table->string('title')->nullable();
            $table->text('content')->nullable();
            $table->text('description')->nullable();
            $table->string('total_of_sessions')->nullable();
            $table->string('durations')->nullable();
            $table->timestamps();
        });
    }

The following is each model for that tables:

#Course model

    class Course extends Model
    {
        use HasFactory,SoftDeletes;
    
        protected $fillable = [
            'title',
            'content',
            'level',
            'start_at',
            'ended_at',
            'capacity',
            'image',
            'url',
            'requirement'
        ];
    
        protected $dates = ['deleted_at'];
    
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    
        public function sections()
        {
            return $this->hasMany(Section::class);
        }
    
        public function category()
        {
            return $this->belongsTo(Category::class);
        }
}

#Section Model

class Section extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

    public function syllabuses()
    {
        return $this->hasMany(Syllabus::class);
    }

    public function course()
    {
        return $this->belongsTo(Course::class);
    }
}

#Syllabus Model

class Syllabus extends Model
{
    use HasFactory;

    public $table = 'syllabuses';

    protected $fillable = [
        'title',
        'content',
        'description',
        'total_of_sessions',
        'durations'
    ];

    public function section()
    {
        return $this->belongsTo(Section::class);
    }
}

And the following is my Route and Controller:

//Route
Route::get('/course/{course}', [App\Http\Controllers\HomeController::class, 'showcourse'])->name('course');

//Display single course page
    public function showcourse(Request $request)
    {
        $course     = Course::with('sections', 'sections.syllabuses')->where('id', $request->route('course'))->first(); ->Your code I have paste
        return view('course-single', [
            'syllabuses' => $syllabuses
            ]);
    }

And the last is my blade:

@foreach($course->sections as $section)
<li >
    <!-- Toggle -->
    <a 
       data-bs-toggle="collapse" href="#course{{ $section->id }}" role="button" aria-expanded="false"
       aria-controls="course{{ $section->id }}">
        <div >
            <!-- Title -->
            {{ $section->name }}
            <p >1/2 hari (2 sesi)</p>
        </div>
        <!-- Chevron -->
        <span >
                          <i ></i>
                        </span>
    </a>
    <!-- Row -->
    <!-- Collapse -->
    <input type="text" value="{{ $section->id }}" name="idsection">
    <div  id="course{{ $section->id }}" data-bs-parent="#courseAccordion">
        @foreach($course->sections as $section)
            @foreach($section->syllabuses as $syllabus)
                <div >
                    <div >
                        <div >
                                            <span >
                                                <i ></i>
                                            </span>
                        </div>
                        <div >
                            <span>{{ $syllabus->title }}</span>
                        </div>
                        <div >
                            <span>2s 180m</span>
                        </div>
                    </div>
                </div>
            @endforeach
        @endforeach
    </div>
</li>
@endforeach

and now I'm stuck to display data from table syllabuses base on Sections's ID, where the sections display base on Courses's ID, because I don't know how to get the ID from each row which related to Secations's ID to put in Syllabus::where('section_id',???)->get();. Anyone who can help me much much appreciate. Hope u understand what I mean.

Below the image you can see, there I have put some note to make u understand. The problem in the green box one.

enter image description here

CodePudding user response:

You need to study laravel relationships in your case you have belongsTo relation.

In your Syllabus model add.

public function section(){
  return $this->belongsTo(Section::class, 'section_id');
}

Then you can use this will get all Syllabuses with related to there sections.

Syllabus::with('section')->get();

CodePudding user response:

Define relations in your models first. I assume your models are: Course, Section and Syllabus

// Model Course
public function sections()
{
     return $this->hasMany(Section::class);
}

// Model Section
public function course()
{
    return $this->belongsTo(Course::class);
}

public function syllabuses()
{
    return $this->hasMany(Syllabus::class);
}

// Model Syllabus
public function section()
{
    return $this->belongsTo(Section::class);
}

Now in your controller you can get your designated course by

// Controller Course

public function show($id)
{
    $course = Course::with('sections', 'sections.syllabuses')->where('id', $id)->first();
}

In this query you have a model from "Course" table, related models from "Sections" table and all the related models from "Syllabuses" table. If you are using laravel's blade then you can simply access them by:

// course
{!! $course->your_attribute !!}

// to access sections
@foreach($course->sections as $section)

@endforeach

// to access syllabuses
@foreach($course->sections as $section)
     @foreach($section->syllabuses as $syllabus)
          // Here you will have syllabuses for individual sections
     @endforeach
@endforeach

https://laravel.com/docs/8.x/eloquent-relationships#one-to-many

  • Related