Search code examples
laravelphpstorm

Best practice in deleting records in Laravel? PhpStorm throws warning


When writing the following code in PhpStorm it warns "Unhandled \Exception":

Flight::where('flight_number', $flight_number)->delete();

This is pretty much exactly how it's documented on Laravel's website. I don't believe this throws an error if no records are found to be deleted?

Should this really be wrapped in a try/catch, with an empty catch since it's not really an error? Especially since in my instance it's fine if no records are found to be deleted.


Solution

  • PhpStorm warns you for a simple reason. The docblock of Illuminate\Database\Eloquent\Model::delete() contains this @throws \Exception annotation:

    /**
     * Delete the model from the database.
     *
     * @return bool|null
     *
     * @throws \Exception
     */
    public function delete()
    

    PhpStorm doesn't care how you call delete() or if flight_number is the PK of the table or not. It couldn't know these things. All it knows is the @throws annotation mentioned above and it tries to be useful by reminding you this thing.

    You can ignore the warning, disable it for the entire project (in Settings -> Editor -> Inspections -> Error handling -> Unhandled exception) or you can disable it only for the statement that calls the delete() method.

    For this last option you can put:

    /** @noinspection PhpUnhandledExceptionInspection */
    

    on a separate line just before the delete() call. This is a special docblock annotation that tells PhpStorm to ignore the unhandled exceptions that could be thrown by the statement that follows it.

    Alternatively, you can put the caret on the delete() call, press Alt-Enter and choose "Add @throws tag" -> "Suppress for statement" from the context menu that opens. It will add the comment for you.

    This is the best way if you know for sure that delete() won't throw any exception (it throws when the model is not properly defined; this is not a runtime error but a coding error; it must never happen after the model was coded).

    Another way to silence it is to add the @throws \Exception annotation in the docblock of the function that contains the call to delete(). This lets PhpStorm know that the exception is not handled at this level and, of course, it will warn you if you don't handle the exception in the code that calls this function.