Search code examples
phpsqllaravelgetcomments

Laravel 5: Fetch comments


I am building a blog commenting system.

I want to show user's comments in show.blade.php.

In my ResultsController I executed

dd($post->comments);

But I cannot retrieve any comments from my database.

I seeded four comments to a post. And user can reply to each one comment.

migration table

Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id');
        $table->integer('post_id');
        $table->text('body');
        $table->integer('comment_id')->nullable();
        $table->timestamps();
    });

Comment.php

public function posts()
{
    return $this->belongsTo(Post::class);
}

public function user()
{
    return $this->belongsTo(User::class);
}

public function replies()
{
    return $this->hasMany(Comment::class, 'comment_id')->whereNotNull('comment_id');
}

Post.php

 public function comments()
{
    return $this->hasMany(Comment::class)->whereNull('comment_id');
}

User.php

public function comments()
{
    return $this->hasMany(Comment::class);
}

Mysql I seeded 4 comments to a post(id=52)

ResultsController.php

 public function show($id,Post $post)
{
    $particular_post= Post::find($id);
    $recommended_posts = Post::latest()
                            ->whereDate('date','>',date('Y-m-d'))
                            ->where('category_id','=',$particular_post->category_id)
                            ->where('id','!=',$particular_post->id)
                            ->limit(7)
                            ->get();

    $posts['particular_post'] = $particular_post;
    $posts['recommended_posts'] = $recommended_posts;

    dd($post->comments);

    return view('posts.show',compact('posts'));
}

http://127.0.0.1:8000/results/52 This is the URL which supposed to fetch comments.


Solution

  • Method injections only work when the variable in the route mapping and the argument for the function have the same name, you also only have to accept the post itself as an argument, you don't need both the post and the id of it.

    Change your show function to this:

    public function show(Post $post)
    {
        $recommended_posts = Post::latest()
                                ->whereDate('date','>',date('Y-m-d'))
                                ->where('category_id','=',$post->category_id)
                                ->where('id','!=',$post->id)
                                ->limit(7)
                                ->get();
    
        $posts['particular_post'] = $post;
        $posts['recommended_posts'] = $recommended_posts;
    
        dd($post->comments);
    
        return view('posts.show',compact('posts'));
    }
    

    And then make sure the variable in the route mapping has the same name as the argument to show, ie:

    Route::get('results/{post}', 'ResultsController@show');