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

Maximus1's avatar

How to block duplication of entries?

How can i avoid duplication of homework answers. See my controller below. I only want students to post an answer for a specific homework just once. Which means after posting, they will be blocked from adding another answer. How can i achieve this?

public function create_homeworkanswer($id){
         //  
           }
public function store(Request $request)
    {
        $homeworkanswer = new \App\HomeworkAnswer();
        $homeworkanswer->date = $request->date;
        $homeworkanswer->student_id = get_studentid();
        $homeworkanswer->homework_id = $request->route_id;
        $homeworkanswer->myanswer = $request->myanswer;
        
        
        $homeworkanswer->save();

This is the route :

Route::get('my_homework/create/{id}', 'Users\HomeworkController@create_homeworkanswer');
Route::post('my_homework/store', 'Users\HomeworkController@store');
0 likes
4 replies
bobbybouwmann's avatar
Level 88

Just check before-hand if they already created an object right?

public function store(Request $request)
{
    $exists = \App\HomeworkAnswer::where('student_id', get_studentid())
        ->where('homework_id', $request->route_id)
        ->exists();

    if ($exists) {
        // You can do here what you want
        return redirect()->route('not-allowed-route');
    }

    $homeworkanswer = new \App\HomeworkAnswer();
    $homeworkanswer->date = $request->date;
    $homeworkanswer->student_id = get_studentid();
    $homeworkanswer->homework_id = $request->route_id;
    $homeworkanswer->myanswer = $request->myanswer;
       
        $homeworkanswer->save();
}

Please or to participate in this conversation.