我想在其类别名称下获取帖子。我在网上尝试了很多教程,但这些教程都不适合我!
这是我的控制器:
public function showcoursecat($slug) {
$coursecateories = course::with('coursecateory')
->where('slug', $slug)
->get();
return view ('frontend.coursecats', compact('coursecateories'));
}
这是我的路线:
Route::get('/courses/cat/{slug}', 'FrontendController@showcoursecat')
->name('coursecat')
->where('slug', '[\w\d\-\_]+');
我的课程模式:
class Course extends Model
{
use Notifiable;
protected $table = "Courses";
protected $fillable = [
'course_name',
'course_description',
'course_price',
'course_disscount',
'slug',
'image',
'category_id',
'user_id',
'approve',
];
protected $events = [
'created' => Events\CourseApproved::class,
];
public function user() {
return $this->belongsTo(User::class);
}
public function coursecateories() {
return $this->belongsTo(Coursecateory::class, 'category_id');
}
}
我的课程模式:
class Coursecateory extends Model
{
protected $fillable = [
'name',
'image',
'slug',
];
public function courses() {
return $this->hasMany(Course::class, 'category_id');
}
}
以下是我的观点:
@foreach($coursecateories as $coursecateory)
<h3>{{ $coursecateory->course_name }}</h3>
@foreach($coursecateory->courses as $course)
<h4><a href="#">{{ $course->course_name }}</a></h4>
<p>{{ $course->course_description }}</p>
@endforeach
@endforeach
答案 0 :(得分:0)
你应该这样做:
$coursecateories = Coursecateory::with('courses')->where('slug', $slug)->get();
在视图中,我认为您的意思是<h3>{{ $coursecateory->name }}</h3>
而不是<h3>{{ $coursecateory->course_name }}</h3>
:
@foreach($coursecateories as $coursecateory)
<h3>{{ $coursecateory->name }}</h3>
@foreach($coursecateory->courses as $course)
<h4><a href="#">{{ $course->course_name }}</a></h4>
<p>{{ $course->course_description }}</p>
@endforeach
@endforeach
<强>更新强>
根据评论的分页需要,您可以这样做:
$category = Coursecateory::where('slug', $slug)->first();
$courses = $category->courses()->paginate(10);
return view('frontend.coursecats', compact('category', 'courses'));
在视图中:
<h3>{{ $category->name }}</h3>
@foreach($courses as $course)
<h4><a href="#">{{ $course->course_name }}</a></h4>
<p>{{ $course->course_description }}</p>
@endforeach