single page in laravel

381 Views Asked by At

I work with Laravel v5.7 !
I have CourseController that controll all things about Courses . all things was ok but now i have problem . in my single page of courses any title or .. returned null .

public function single(Course $course)
{
    $course = Course::get()->first();
    $comments = $course->comments()
        ->where('approved', 1)
        ->where('parent_id', 0)->latest()
        ->with('comments')->get();
    return view('Home.course', compact('course', 'comments'));
}

Here is my controller code . when i use first() at all my singlepage i have same title and image ,..... and if i delete the first() u have this error :

Method Illuminate\Database\Eloquent\Collection::comments does not exist.

I use {{ $course->title }} for showing course data in singlepage . but for all slugs and courses return only first row of Db .

Please help me if you can ! ThankYou

2

There are 2 best solutions below

4
Niko Peltoniemi On

You are currently overwriting the $course variable with the first instance in the database.

public function single(Course $course)
{
    // $course = Course::get()->first(); <- This gets the first Course also if you use first, don't use get
    $comments = $course->comments
        ->where('approved', 1)
        ->where('parent_id', 0)
        ->latest()
        ->with('comments')
        ->get();
    return view('Home.course', compact('course', 'comments'));
}
3
adwairi On

This will return the first course with its comments, and you can call $course->title directly in your blade.

public function single(Course $course)
{
    $course = Course::with(['comments' => function($query){
        $query->where('approved', 1)->where('parent_id', 0);
    }])->fisrt();
    $comments = $course->comments;
    return view('Home.course', compact('course', 'comments'));
}

OR

This will return all courses which have comments approved and parent_id = 0, and in your blade you have to make a loop on courses:

Controller:

public function single(Course $course)
{
    $courses = Course::with(['comments' => function($query){
        $query->where('approved', 1)->where('parent_id', 0);
    }])->get();
    return view('Home.course', compact('courses'));
}

blade:

@foreach($courses as $course)
    {{ $course->title }}
    $foreach($course->comments as $comment)
          {{ $comment->id }}
    @endforeach
@endforeach