Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stevendeenstra's avatar

Request sometimes null

Good morning! I have an error in my application which I just can't manage to fix.

The application is basically a multiple choice quiz. All questions (around 60 per quiz) are pre-loaded on the page and every answer is submitted with an Ajax call.

The Ajax request has two post variables: question_id, answer. The Ajax creates a POST request to a Controller, which in turn calls a Repository that should save the given answer in the Database.

However, if I check my logs I see that the Request value sometimes is null and I really don't know how this is possible.

Here is part of the code:

An Ajax request with CSRF header and POST data is submitted to the saveAnswer() method below:

class AnswerController extends Controller
{
    /**
     * @var UserAnswerRepository
     */
    protected $user_answer;

    /**
     * AnswerController constructor.
     * @param UserAnswerRepository $user_answer
     */
    public function __construct(UserAnswerRepository $user_answer)
    {
        $this->user_answer = $user_answer;
    }

    /**
     *
     */
    public function saveAnswer()
    {
        $this->user_answer->store();
    }
}

Then in the UserAnswerRepository the store method is called to save the given answer to the database:

    public function store()
    {   
            UserAnswer::create([
                'question_id' => request('question'), // question = question_id
                'test_session_id' => session()->get('test_session'),
                'answer' => request('answer')
            ]);
    }

The error was thrown because question_id and answer are null.

Can someone help me?

0 likes
7 replies
s4muel's avatar

you say:

...The Ajax request has two post variables: question_id, answer....

you mean question_id? because in the store() method, you use question:

'question_id' => request('question'),

might this be the cause?

D9705996's avatar

As well as ensuring you are passing the correct parameter names as suggested you really should be validating the request before trying to persist in you database. Rather than using request() you can typehint the request in your store method and then


public function store(Request $request)
{
    $validatedData = $request->validate([
        'question_id' => 'required|exist:questions',
        'answer' => 'required|in,A,B,C,D',
    ]);

    UserAnswer::create([
         'question_id' => $validatedData->question_id
          'test_session_id' => session()->get('test_session'),
          'answer' => $validatedData->answer
      ]); 
}

The above will return a 422 error with why your request is failing in the JSON response which you can inspect in you browxer ddv tools to find out why. It also ensures that the question exists and the answer was A, B, C or D. I dont know the way you store the answers so you need to adapt to your world but all the validation rules are here

https://laravel.com/docs/5.7/validation#available-validation-rules

stevendeenstra's avatar

Thank you for your responses.

@s4muel : request('question') is right. AJAX sends the question_id in the question variable. I should change it for more clarity.

@D9705996 : Validation is a good idea indeed. I will implement it, thanks for the suggestion. However, this does not explain why Request sometimes is null. Relatively seen, this error does not occur a lot.

There are 600K+ answers submitted and the Request = null error is thrown 1.1K times.

D9705996's avatar

There must be something happening in your Front end code causing this. You need to find out if there is any commonality in the failing requests, e.g. specific question, quiz, etc.

If you can find this you can narrow in on the solution. Can you reliably replicate the fault so it happens every time? If so can you add logging to console.log the ajax request and response.

stevendeenstra's avatar

I've inspected the front-end code and could not find something that could lead to this problem. Also, I logged the error in Sentry and I've found the following:

if(is_null($question_id) OR is_null($answer)) {
            app("sentry")->captureMessage("Vars are empty: question_id OR answer. Got request: " . print_r(request()->all(), 1));
        }

In Sentry the following is logged:

Vars are empty: question_id OR answer. Got request: Array
(
)

Which basically means that request() is empty. Is it possible that the CSRF token is expired or something like this? What else can I log to get closer to the problem?

munazzil's avatar

@stevendeenstra

Use as like below and check.

 public function store(Request $request)
        {   
            UserAnswer::create([
             'question_id' => $request('question'), // question = question_id
              'test_session_id' => session()->get('test_session'),
              'answer' => $request('answer')
            ]);
     }
D9705996's avatar

@stevendeenstra - are you able to add logging to you front end to log the data being passed by Ajax to the backend. If the data isn't being sent then you can rule out your backend code until younresolve the front end issue.

I would also log all of the requests go sentry for the front end. The more data you have the easier it will be go spot commonality in why this is failing.

Please or to participate in this conversation.