Home > database >  Laravel: Too few arguments to function
Laravel: Too few arguments to function

Time:10-05

In my Laravel app, I have answers which are related to questions. In my controller I have a function to retrieve the user's answers.

While running this function, I have an error saying

'too few arguments to function'.

The issue is with the $userId, but I don't know why. This argument is not 'accepted' in my with 'method'.

Please help me out here.

public function get_user_answers($phaseId, $stepId, $userId)
    {
        $questions = Question::where('step_id', $stepId)
        ->with(array('answers' => function($query, $userId) {
            $query->where('user_id', $userId);
        }))
        ->get();

        if($questions) {
            return response()->json([
                'questions' => $questions,
            ], 200);
        } else {
            return response()->json([
                'message' => 'No questions were found.',
            ], 404);
        }
    }

CodePudding user response:

You cannot pass a outer parameter in callback function. You can try by using use like-

        ->with(array('answers' => function($query) use ($userId) {
            $query->where('user_id', $userId);
        }))

So after this change, your code will look like,

public function get_user_answers($phaseId, $stepId, $userId)
    {
        $questions = Question::where('step_id', $stepId)
        ->with(array('answers' => function($query) use ($userId) {
            $query->where('user_id', $userId);
        }))
        ->get();

        if($questions) {
            return response()->json([
                'questions' => $questions,
            ], 200);
        } else {
            return response()->json([
                'message' => 'No questions were found.',
            ], 404);
        }
    }
  • Related