Search code examples
phplaravellaravel-routinglaravel-8

Laravel Too few arguments in function Model::destroy()


I'm setting up a delete route in Laravel 8.6.0 like this:

api.php

Route::delete('code-rule/{id}', 'api\v1\CodeRuleController@destroy');

CodeRuleController.php

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\CodeRule  $codeRule
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        return response()->json(CodeRule::where('id', $id)->first()->destroy());
    }

Now when I try a delete request in postman to the url localhost:8080/api/v1/code-rule/13/ I get the following response:

ArgumentCountError: Too few arguments to function Illuminate\Database\Eloquent\Model::destroy(), 
0 passed in C:\Ontwikkeling\TenT en Batchcontrol\API\app\Http\Controllers\api\v1\CodeRuleController.php
on line 112 and exactly 1 expected in file 
C:\Ontwikkeling\TenT en Batchcontrol\API\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php 
on line 905

I have no idea why this is happening, when I google this I only get people wanting to pass more arguments, not the problem i'm facing.


Solution

  • The destroy() method accept an argument destroy($primaryKey), to delete model instance, like :

    CodeRule::destroy(1);
    CodeRule::destroy(1, 2, 3);
    

    You can use destroy() method like this way :

    CodeRule::destroy($id);
    

    Or you can use delete() method instead :

    CodeRule::where('id', $id)->first()->delete();
    

    The destroy() method loads each model individually and calls the delete() method on them so that the deleting and deleted events are fired.