Home > other >  deleting from the database does not work with apis in laravel
deleting from the database does not work with apis in laravel

Time:07-06

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

CodePudding user response:

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.

CodePudding user response:

I do not know what is the error, but I would suggest to try without "/api" on your route

Route::delete('/deletepatient/{id}',[ApisController::class,'deletePatient']);

I would do it like that:

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

     return response()->json([
          "message" => "Patient has been deleted"
     ], 200);        
    
  }

CodePudding user response:

Please try clear your cache:

php artisan optimize
php artisan route:clear
php artisan config:cache
php artisan cache:clear
  • Related