Issue
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
Solution
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!
Answered By - Vinayak Sarawagi Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.