我作为路由参数传递的模型未被读取(Laravel)

Posted

技术标签:

【中文标题】我作为路由参数传递的模型未被读取(Laravel)【英文标题】:The model I passed as route parameter isn't being read (Laravel) 【发布时间】:2022-01-11 08:16:55 【问题描述】:

在我的应用程序中,求职者复习考试后,会创建一个新的 jobseekerExamReview 实例并将其存储到 $examReview 变量中以存储他们的分数。然后将它们重定向到显示所述考试复习结果的新页面,因此我将$examReview 作为参数传递给结果路由。 id 显示在链接中并且有效,但考试内容不会显示,因为值显然为空。我检查了新记录的所有列,它们都有数据。当我最终对$examReview 执行dd 时,它返回空。

$examReview(控制器)的值:

// create new Exam review session
$examReview = jobseekerExamReview::create([
    'jobseeker_id' => $jobseeker->id,
    'exam_id' => $exam_id
    //upon creation 'results' are set to 0 at default and updated later after score calculation (see full code)
]);

在控制器中重定向:

// return view to review results with answered and correct
return redirect()->route('showResults', [$examReview]);

web.php

Route::get('/exam/reviewExam/results/jobseekerExamReview:id', [reviewExamController::class, 'showResults'])
    ->middleware(['auth','verified'])
    ->name('showResults');

控制器中的完整代码:

public function calculateResult()

    // get needed details
    $jobseeker = Jobseeker::findorFail(auth()->user()->id);
    $exam_id = request()->input('exam_id');
    $jobApplication = jobApplication::find(session('jobApplicationId'));
    $correctAnswers = 0;

    // create new Exam review session
    $examReview = jobseekerExamReview::create([
        'jobseeker_id' => $jobseeker->id,
        'exam_id' => $exam_id
    ]);

    // loop through each question taken by user
    foreach(request()->input('taken_questions') as $key => $question_id)
        // is answer correct or not
        // echo "<br>Question ID: ".$question_id;
        $status = 0;
        //answer[questionID] => answer_id
        // if the answer[questionID] is not emptu and matched answer ID is correct
        // echo "<br>Answer ID:".request()->input('answer.'.$question_id);
        if((request()->input('answer.'.$question_id) != null) && (examAnswer::find(request()->input('answer.'.$question_id))->isCorrect == true))
            // answer is correct
            // echo "is Correct";
            $status = 1;
            $correctAnswers++;

            // create review Exam Answers
            jobseekerExamReviewAnswer::create([
                'exam_review_id' => $examReview->id,
                'question_id' => $question_id,
                'answer_id' => request()->input('answer.'.$question_id),
                'isCorrect' => $status
            ]);

        
    

    // calculate score
    $percentScore = $correctAnswers/count(request()->input('taken_questions'))*100;
    // update score in review
    $examReview->update(['result' => $percentScore]);
    // return view to review results with answered and correct
    return redirect()->route('showResults',[$examReview]);


public function showResults(jobseekerExamReview $examReview)

    return view('exams.exam-review-results',[
        'examReview' => $examReview
    ])->with('reviewExamAnswers');

【问题讨论】:

【参考方案1】:

您的方法签名(路由操作)中的类型提示变量的名称必须与路由定义中的路由参数名称相匹配。您的路由参数名为jobseekerExamReview,但控制器方法的参数名为jobseeker,不匹配。因此,您将获得一个新的不存在的jobseekerExamReview 实例@ 注入(依赖注入)而不是路由模型绑定。您应该调整您的路线参数以匹配:

Route::get('/exam/reviewExam/results/examReview:id', ...);

这将导致发生隐式路由模型绑定而不是依赖注入。

“Laravel 自动解析定义在路由或控制器操作中的 Eloquent 模型,其类型提示的变量名称与路由段名称匹配。”

Laravel 8.x Docs - Routing - Route Model Binding - Implicit Binding

附带说明一下,在将参数传递给 URL 助手时,您应该养成使用关联数组的习惯,例如 route,这样它就可以准确地知道您传递的是什么参数:

return redirect()->route('showResults', ['examReview' => $examReview]);

【讨论】:

以上是关于我作为路由参数传递的模型未被读取(Laravel)的主要内容,如果未能解决你的问题,请参考以下文章

如何在Laravel 5.2中将表单数据作为路由参数传递

如何将 vue.js 值作为参数传递给刀片中的路由

Laravel - 通过路由传递参数后Javascript不起作用

Laravel 将参数从路由传递到过滤器

Laravel 将 url 参数从控制器传递到路由

Laravel 5.2 使用 uuid 字符串作为 id 的隐式路由模型绑定