Ihtisham Khan
Ihtisham Khan

Reputation: 445

How do I retrieve course contents of the specific course in Laravel?

I am creating an online course site. I have issue with retrieving the course content of a specific course.

This function shows all the contents of different courses as well. I want to show the content of a specific course instead.

public function index()
{
    $contents = Content::all();
    return view('content.index', compact('contents'));
}

This is my content model.

class Content extends Model
{

protected $fillable = [
    'topic', 'content',
];

public function course()
{
    return $this->belongsTo('App\Course');
}
}

Thsi is course model.

class Course extends Model
{
    protected $fillable = [
        'title', 'about', 'image',
    ];

public function contents(){
    return $this->hasMany('App\Content');
}
}

Content Migration

public function up()
{
    Schema::create('contents', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('course_id');
        $table->string('content');
        $table->string('topic');
        $table->timestamps();
    });
}

Content index blade

@foreach ($contents as $content)
  <div class="col-lg-12 content-list">
    <a href="/content/{{$content->id}}">
      <div class="cl-item mb-2" style="border-radius: 8px; padding: 18px; background-color: #c2c6ca;">
      <h4 class="m-0">{{$content->topic}}</h4>
      </div>
    </a>
  </div>
@endforeach

Upvotes: 0

Views: 663

Answers (2)

Vinayak Sarawagi
Vinayak Sarawagi

Reputation: 1062

You need to create a route in web.php like following:

Route::get('/courses/{course_id}/contents', 'ContentController@get')->name('web.course_contents');

In the above code base, we pass "course_id" param for which we want to fetch the contents for.

In ContentController.php, do the following:

class ContentController extends Controller
{
    get($course_id)
    {
        $contents = Content::where('course_id', $course_id)->get();
        return view('content.index', compact('contents'));
    }
}

Content::where('course_id', $course_id)->get() will run select * from contents where course_id = ? query to your database. You can check this by doing the following:

class ContentController extends Controller
{
    get($course_id)
    {
        $contents = Content::where('course_id', $course_id)->get();
        logger(Content::where('course_id', $course_id)->toSql());
        return view('content.index', compact('contents'));
    }
}

You can learn more about Laravel Query Builders here.

Happy Coding!

Upvotes: 1

Humza Faqi
Humza Faqi

Reputation: 241

For this, all you need to do is use with to fetch both contents and their courses at the same time as:

public function index()
{
    $contents = Content::with('course')->get();
    return view('content.index', compact('contents'));
}

For more information, you can visit this link: https://laravel.com/docs/6.x/eloquent-relationships#eager-loading

Upvotes: 0

Related Questions