How to call member function delete() on null Laravel 8

It is obvious for every Laravel application to have a delete function. But, you might have noticed a usual error using while deleting records, that comes while you use the deletion operation on null records. Let us look at some methods to properly call member function delete() to avoid this error.

Best Approaches to call member function delete() on null

If a typical delete() member function in your Controller Class is defined as follows.

public function deletePost($post_id)
{
    $post = Post::where('id',$post_id)->first();
    $post->delete();
    return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted post!!']);
} 

We can handle errors on calling delete() on null records in various ways that are explained below.

Method 1

You can add a condition before calling the delete() function, to confirm if the post actually exists before passing the function to it, as shown below.

public function deletePost($post_id)
{
    $post = Post::where('id',$post_id)->first();
    if ($post != null) {
        $post->delete();
        return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted post!!']);
    }
    return redirect()->route('dashboard')->with(['message'=> 'No such posts exists!!']);
} 

Method 2

Another method to use the member function delete() is to change the first() function assigned to the $post variable to firstOrFail(). This checks the first matching record and if now record is found, it aborts the process, thereby shortening the code and avoiding errors that come due to deletion of null records.

public function deletePost($post_id)
{
    $post = Post::where('id',$post_id)->firstOrFail();
    $post->delete();
    return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
}

Method 3

Use of Route Model Binding is another solution where you can define a route as follows.

$router->model('post', 'App\Post');

Then add the following details in your route.

Route::post('post/{post}/delete', [
    'as' => 'post.delete', 'uses' => 'PostController@deletePost'
]);

Then add the following in your controller.

public function deletePost(Post $post)
{
    $post->delete();
    return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted post!!']);
}