Search code examples
laravelpostgresqllaravel-8delete-rowrest

Laravel API delete row from db


While trying to delete rows by id from db as below , I am getting the error- count(): Parameter must be an array or an object that implements Countable. I think no id is passed to the delete() function in my code and am not sure how to pass it. Please help me with ur suggestions.

Controller

public function delete($id){
            
            
            $data = PersonalDetails::where('id',$id)->delete();
            // dd($data);
            if(count($data)){
    
                return response()->json(['message'=>'Successfully Deleted']);
            }
            else{
                return response()->json(['message'=>'Delete Failed']);
            }
        }

Route

Route::group([
    'namespace'=>'App\Http\Controllers',
    'middleware' => 'api',
], function ($router) {

    Route::post('delete/{id}', 'PersonalDetailsAdmin@delete');
}

Solution

  • The ->delete() method already returns the count of the deleted rows, so the solution would be:

    public function delete($id){
        
        $count = PersonalDetails::where('id',$id)->delete();
        // dd($data);
        if($count > 0 ){
    
            return response()->json(['message'=>'Successfully Deleted']);
        }
        else{
            return response()->json(['message'=>'Delete Failed']);
        }
    }