Search code examples
laravelapilaravel-9

deleting from the database does not work with apis in laravel


The process of deleting from the database does not work with apis in laravel I created a function that deletes from database but my code doesn't work

  public function deletePatient($id) 
    {  
         $patient =Patient::find($id);
          if(!sizeof($patient)==0) {
            $patient->delete();
          return response()->json([
            "message" => "Patient is  deleted"
          ], 200);
        } else {
          return response()->json([
            "message" => "Patient not found"
          ], 404);
        }
      }

route

use App\Http\Controllers\Admin\Api\ApisController;
Route::delete('/api/deletepatient/{id}',[ApisController::class,'deletePatient']);

Postman Delete : http://localhost:8000/api/deletepatient/4


Solution

  • You appear to be complicating things a bit, try the following:

    public function deletePatient(Patient $id)
    {
        if (!$patient->delete()) {
            return response()->json(['message' => 'Failed to delete patient'], 404);
        }
    
        return response()->json(['message' => 'Patient deleted'], 204);
    }
    

    We're using route model binding to have Laravel automatically find the relevant Patient model from the database for us, if one is not found it will throw a 404 - Not Found error for us. Alternatively you could use Patient::findOrFail($id); if you wanted to.

    If the delete operation was not successful, return an error response (you can customise this to your liking), otherwise return a success response. Usually this is a 204 - No Content.