laravel: Call to a member function delete() on null

I got this error when I tried to add a feature of delete, to the posts just by clicking on the delete button. Where am I doing wrong?

Delete post function in PostController:

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

Upvotes: 4

Views: 67754

Answers (4)

Victor
Victor

Reputation: 1041

$postobject is null. Maybe you are sending a wrong $post_id. If you check that the post exists before delete you avoid that error.

public function getDeletePost($post_id)
{
    $post =Post::where('id',$post_id)->first();

    if ($post != null) {
        $post->delete();
        return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
    }

    return redirect()->route('dashboard')->with(['message'=> 'Wrong ID!!']);
} 

Upvotes: 15

Marek Skiba
Marek Skiba

Reputation: 2184

It looks like you don't have Post where id = $post_id, you can try with firstOrFail method:

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

or start using Route Model Binding and then you don't need care about that Post with id = $post_id exist or not:

So first you need add binding in the RouteServiceProvider::boot:

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

then in route you need change to this:

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

and then your controller looks like this:

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

If you have still problem, you should show us how you build POST form that send request to the controller.

Upvotes: 2

Saurabh
Saurabh

Reputation: 469

You eloquent query is not returning a result so the $post variable is empty which is causing the error.

Instead use findOrFail which will throw exception if no record is found with provided id.

$post = Post::findOrFail($id);
$post->delete();
return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);

If ModelNotFound exception is thrown then that means Post record does not exist in database with the provided Id.

Upvotes: 0

ptorsson
ptorsson

Reputation: 488

There is a chance that your $post variable is null/undefined.

public function getDeletePost($post_id) {
  try {
    $post = Post::where('id',$post_id)->first();
  } catch (ModelNotFoundException $e) {
    return redirect()->route('dashboard')->with(['message'=> 'Failed']);
  }

  $post->delete();

  return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
} 

Upvotes: 1

Related Questions