-2

I'm encountering a peculiar issue in my Laravel API setup. I have a resource controller for managing student data, including deletion. When I make a DELETE request to http://127.0.0.1:8000/api/student/1 (for example, with id=1), the first request successfully deletes the student and returns a JSON response with a success message:

{
    "message": "Student deleted successfully"
}

However, if I make another DELETE request immediately afterward with the same URL and ID, instead of receiving a similar success message, I get a 404 Not Found error with a rendered HTML response.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Not Found</title>

    <style>
        /* code css here */
    </style>
    <link rel='stylesheet' type='text/css' property='stylesheet'
        href='//127.0.0.1:8000/_debugbar/assets/stylesheets?v=1697098252&theme=auto' data-turbolinks-eval='false'
        data-turbo-eval='false'>
    <script src='//127.0.0.1:8000/_debugbar/assets/javascript?v=1697098252' data-turbolinks-eval='false'
        data-turbo-eval='false'></script>
    <script data-turbo-eval="false">
        jQuery.noConflict(true);
    </script>
    <script>
        //js code here 
    </script>
</head>

<body class="antialiased">
    <div
        class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center sm:pt-0">
        <div class="max-w-xl mx-auto sm:px-6 lg:px-8">
            <div class="flex items-center pt-8 sm:justify-start sm:pt-0">
                <div class="px-4 text-lg text-gray-500 border-r border-gray-400 tracking-wider">
                    404 </div>

                <div class="ml-4 text-lg text-gray-500 uppercase tracking-wider">
                    Not Found </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        //js script code
    </script>
</body>

</html>

The code of the Controller function

// StudentController.php

<?php

use App\Models\Student;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class StudentController extends Controller
{
    // ...other code 

    public function destroy(Student $student)
    {
        try {
            $student->delete();
            $student->person()->delete();
            $student->guardian1()->delete();
            $student->guardian2()->delete();
            return response()->json(['message' => 'Student deleted successfully'], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $notFoundException) {
            return response()->json(['error' => 'Student not found', 'exception' => $notFoundException->getMessage()], 404);
        } catch (\Exception $e) {
            return response()->json(['error' => 'An error occurred while deleting the student', 'exception' => $e->getMessage()], 500);
        }
    }
}

the Code of the Api Route

// api.php

<?php

use Illuminate\Support\Facades\Route;

Route::group(['middleware' => 'auth:api'], function(){
    // ...other code 

    Route::resource('student', App\Http\Controllers\StudentController::class);
 
});

Additional Information:

  • This behavior occurs consistently whenever I attempt to delete a student for the second time.
  • I've ensured that the appropriate routes are registered in api.php.
  • I'm using Laravel version 10.32.1

I expected that both DELETE requests would successfully return a JSON response with a message indicating successful deletion, or Error message of not exists element.

2
  • Make sure to alias the exception class you are checking for. laravel use Illuminate\Database\Eloquent\ModelNotFoundException; Without this you are checking for an instance of App\Exceptions\ModelNotFoundException. Commented Mar 31, 2024 at 6:58
  • 1
    the record has been deleted already so it doesn't exist ... route model binding happens before your controller method is called ... also how are you making this request to your api? as you would need the correct headers for the server to know you expect json as a response Commented Mar 31, 2024 at 12:02

2 Answers 2

0

I understand you:

public function destroy(Student $student)

It's Laravel implicit binding, this means when you call this function It's doing behind the scenes something like Student::find($student->id) and this returns you error 404 because It's already deleted so you can't catch it here :)

You can change it to destroy($id) and do more work manually or change it to custom model binding: https://laravel.com/docs/11.x/routing#customizing-the-resolution-logic

Sign up to request clarification or add additional context in comments.

Comments

0

Make sure to alias the exception class you are checking for.

use Illuminate\Database\Eloquent\ModelNotFoundException;

Without this you are checking for an instance of App\Exceptions\ModelNotFoundException.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.