создание раздела для тестирования, где это могут делать зарегистрированные пользователи, но в настоящее время тест можно выполнять много раз, и я бы хотел, чтобы они могли сделать это только один раз

#laravel

#laravel

Вопрос:

Я использую laravel 7

Мне нужно, чтобы, если пользователь уже прошел тест, загрузите другое другое представление

Это мой тестовый контроллер

     public function index()
    {
        $categories = Category::with(['categoryQuestions' => function ($query) {
                $query->orderBy('id')
                    ->with(['questionOptions' => function ($query) {
                        $query->orderBy('id');
                    }]);
            }])
            ->whereHas('categoryQuestions')
            ->get();

        return view('client.test', compact('categories'));
    }

    public function store(StoreTestRequest $request)
    {
        $options = Option::find(array_values($request->input('questions')));

        $result = auth()->user()->userResults()->create([
            'total_points' => $options->sum('points')
        ]);

        $questions = $options->mapWithKeys(function ($option) {
            return [$option->question_id => [
                        'option_id' => $option->id,
                        'points' => $option->points
                    ]
                ];
            })->toArray();

        $result->questions()->sync($questions);

        return redirect()->route('client.results.show', $result->id);
    }
}
  

Таким образом таблица результатов подключается к таблице пользователей

Это моя миграция, чтобы добавить связь с таблицей пользователей;

     class AddRelationshipFieldsToResultsTable extends Migration
{
    public function up()
    {
        Schema::table('results', function (Blueprint $table) {
            $table->unsignedInteger('user_id');

            $table->foreign('user_id', 'user_fk_773765')->references('id')->on('users');
        });
    }
}
  

Ответ №1:

Обновите свой метод index, чтобы проверить таблицу результатов. Предполагая, что у вас есть Result модель для вашей results таблицы.

 public function index()
{
    $existingTest = Result::where('user_id', Auth::user()->id)->first();
    if(isset($existingTest->id)) {
        //Return your other view or run logic specific to if the user has already done the test.
        return view('client.test-complete');
    }

    $categories = Category::with(['categoryQuestions' => function ($query) {
        $query->orderBy('id')
            ->with(['questionOptions' => function ($query) {
                $query->orderBy('id');
            }]);
    }])->whereHas('categoryQuestions')
       ->get();

    return view('client.test', compact('categories'));
}