Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

laravel

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!!']);
} 
like image 460
Learning_to_solve_problems Avatar asked Dec 08 '22 20:12

Learning_to_solve_problems


1 Answers

$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!!']);
} 
like image 130
Victor Avatar answered Dec 11 '22 10:12

Victor