Search code examples
phpmysqllaravellaravel-5laravel-5.3

LARAVEL - Not able to call a function inside a controller method


Here is comment method of CommentController

public function comment(Request $request)
{

    $comments = DB::table('comments')
                    ->join('answers', 'answers.id' , '=', 'comments.answer_id')
                    ->join('users' , 'users.id' , '=', 'comments.user_id')
                    ->where('answers.id', '=' , '9')
                    ->where('parent_id', '0')
                    ->select('comments.comment as comment',
                             'comments.id as comment_id',
                             'comments.created_at as created_at',
                             'comments.parent_id as parent_id',
                             // 'answers.aanswer as answer',
                             'answers.id as ans_id')
                    ->orderBy('created_at', 'desc')
                    ->get();


    foreach ($comments as $comment) {
         echo $comment->comment_id.$comment->comment.'<br>';
        return $this->testingComment();
    }


    public function testingComment(){
        echo "testing comments function";
    }

}

I have this foreach loop , I am just t trying to call this testingComment function in loop, but its not working.

I am building a nested comment system and i want to call function inside foreach loop to render child and sub child comments when a when a parent_id matches


Solution

  • Please copy and paste the below code it will works fine and you missed some }:

    public function comment(Request $request)
    {
    
          $comments = DB::table('comments')
                            ->join('answers', 'answers.id' , '=', 'comments.answer_id')
                            ->join('users' , 'users.id' , '=', 'comments.user_id')
                            ->where('answers.id', '=' , '9')
                            ->where('parent_id', '0')
                            ->select('comments.comment as comment',
                                    'comments.id as comment_id',
                                    'comments.created_at as created_at',
                                    'comments.parent_id as parent_id',
                                    // 'answers.aanswer as answer',
                                    'answers.id as ans_id')
    
                            ->orderBy('created_at', 'desc')
                            ->get();
    
    
           foreach ($comments as $comment) {
              echo $comment->comment_id.$comment->comment.'<br>';
              return $this->testingComment();
           }
    
    }
    
    public function testingComment(){
                    echo "testing comments function";
    
    }