DEV Community

Syntax Byte Solutions
Syntax Byte Solutions

Posted on

Page keep redirecting back to the same page while it should be redirected to another page in Laravel Project

I have a method that should collect test answers (Yes or No) from the form, calculate the results, and insert them into the Database Table. But once the user clicks on submit, it will redirect back to the same question page. Below is the code:

`
public function storeAnswer(Request $request, $id) {

    $questions = Question::with('category')->get();

    if ($request->isMethod('post')) {
        $answers = $request->input('answer');

        //$request->dd();

        $passCountByCategory = [];

        foreach ($questions as $question) {
            $answer = $answers[$question->id] ?? null;

            if ($answer === 'Yes') {
                $categoryId = $question->category->id;
                $passCountByCategory[$categoryId] = ($passCountByCategory[$categoryId] ?? 0) + 1;
            } elseif ($answer === 'No') {
                $categoryId = $question->category->id;
                $passCountByCategory[$categoryId] = ($passCountByCategory[$categoryId] ?? 0);

            } else {

                return redirect()->back()->with('error', 'You did not choose any options');
            }
        }

        $overallPassed = 0;
        $overallTotal = 0;

        foreach ($passCountByCategory as $categoryId => $passCount) {
            $category = Category::find($categoryId);
            $categoryTotal = count($category->questions);
            $categoryPassed = $passCount;

            $categoryResult = new CategoryResult();
            $categoryResult->result_id      = $id;
            $categoryResult->category_name  = $category->name;
            $categoryResult->pass_count     = $categoryPassed;
            $categoryResult->total_count    = $categoryTotal;
            $categoryResult->percentage     = ($categoryPassed / $categoryTotal) * 100;
            $categoryResult->category_status = ($categoryPassed >= 2) ? 'Passed' : 'Failed';
            $categoryResult->save();

            $overallPassed += $categoryPassed;
            $overallTotal += $categoryTotal;
        }

        $overallPercentage = ($overallPassed / $overallTotal) * 100;
        $overallStatus = ($overallPercentage >= 66) ? 'Passed' : 'Failed';

        $testResult = new TestResults();
        $testResult->app_id         = $id;
        $testResult->pass_count     = $overallPassed;
        $testResult->total_count    = $overallTotal;
        $testResult->percentage     = $overallPercentage;
        $testResult->status         = $overallStatus;
        $testResult->save();

        $app_name = UserApps::where('app_id', $id)->value('app_name');

        $appStatus = ($overallStatus === 'Passed') ? 'Certified' : 'Unapproved';
        UserApps::where('app_id', $id)->update(['status' => $appStatus]);

        return redirect()->route('test.results', ['id' => $id]);
    }

}`
Enter fullscreen mode Exit fullscreen mode

What could have been the issue?

Apparently, this is the getResults method:

`
public function getResults($id) {

    $testResult = TestResults::findOrFail($id);
    $categoryResults = CategoryResult::where('result_id', $id)->get();

    return view('result_view', compact('testResult', 'categoryResults'));

}`
Enter fullscreen mode Exit fullscreen mode

Here are my two routes:
`
Route::post('/user/store-results/{id}', [QuestionController::class, 'storeAnswer'])->name('store_results');

Route::get('/user/results-test/{id}', [QuestionController::class, 'getResults'])->name('test.results');`

I could not figure out what could be the problem.

I $request->dd(), got the answer from the form:

Image description

Top comments (2)

Collapse
 
timoye profile image
Timothy Soladoye

From the json you shared, $answer in the code will be an array not a string.

$answer = $answers[$question->id] ?? null;
Enter fullscreen mode Exit fullscreen mode

The array will be

$answer=
[3=>"Yes",
4=>"Yes",
5=>"Yes"];
Enter fullscreen mode Exit fullscreen mode

So when you do a check in

 if ($answer === 'Yes') 
 elseif ($answer === 'No') 
Enter fullscreen mode Exit fullscreen mode

it will always run the else and redirect


else {
    return redirect()->back()->with('error', 'You did not choose any options');
      }
Enter fullscreen mode Exit fullscreen mode

By the way, I prefer to structure my code using services
blog.quickadminpanel.com/laravel-w...

I can assist it over a google meet if you need assistance
Cheers

Collapse
 
arianygard profile image
AriaNygard

Honestly I don't know but I hope someone that does sees your post! Good luck :)