KB_Shayan
KB_Shayan

Reputation: 652

Laravel: Can't delete a post created by the user

So a user has the ability to delete a post they created. However, when I click delete I get an error stating that there isn't anything there to delete and I can't figure out why this is the case.

This is the error:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function delete() on null

Below is my post controller class, I don't understand why $post = Post::where('id', $post_id)->first(); returns null.

class PostController extends Controller
{
    public function getDashboard(){
        $posts = Post::all();
        return view('dashboard', ['posts' => $posts]);
    }

    public function postCreatePost(Request $request){
        $this->validate($request, [
            'body' => 'required'
        ]);

        $post = new Post(); 
        $post->body = $request['body'];
        $message = 'There was an error';
        if($request->user()->posts($post)->save($post)){; //points here
            $message = 'post successfully created';
        }
        return redirect()->route('dashboard')->with(['message' => $message]);
    }

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

This is my dashboard.blad.php view:

<section class="row new-post">
    <div class="col-md-6 col-md-offset-3">
        <header><h3>What do you have to say</h3></header>
        <form action="{{ route('postcreate') }}" method="post">
            <div class="form-group">
                <textarea class="form-control" name="body" rows="5" placeholder="your post"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Create post</button>
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
        </form>
    </div>
</section>

<section class="row posts">
    <div class="col-md-6 col-md-offset-3">
        @foreach($posts as $post)
            <article class="post">
                <p>{{ $post->body }}</p>
                <div class="info">posted by {{ $post->user->email }} on {{ $post->created_at }}</div>
                <div class="interaction">
                    <a href="#" class="post-item">Like</a>
                    <a href="#" class="post-item">Edit</a>
                    <a href="{{ route('post.delete', ['post_id => $post->id']) }}" class="post-item">Delete</a>
                </div>
            </article>
        @endforeach
    </div>
</section>

My Web Routes:

Route::get('/', function () {
    return view('landing');
});

Route::get('/user', function () {
    return view('User/usersignup');
});


Route::post('/signup', 'UserController@postSignUp')->name('signup');

Route::post('/signin', 'UserController@postSignIn')->name('signin');

Route::get('/dashboard', 'PostController@getDashboard')->name('dashboard');

Route::post('/createpost', 'PostController@postCreatePost')->name('postcreate');

Route::get('/delete-post/{post_id}', 'PostController@getDeletePost')->name('post.delete');

Upvotes: 1

Views: 1282

Answers (1)

Elias Soares
Elias Soares

Reputation: 10254

Your problem is almost the same of your last question, so I presume that you need to learn to understand the error messages.

Call to a member function delete() on null. (On line XXX)

The message says everything you need to know!

On line XXX:

public function getDeletePost($post_id){
    $post = Post::where('id', $post_id)->first();
    $post->delete(); // That should be the line XXX
    return redirect()->route('dashboard')->with(['message' => 'post deleted']);
}

The error says that you are trying to call the method delete() on a null variable. This tell you that the $post variable is null. Simple enough.

Okay, but why it's null?

It's null probably because the Post model doesn't contain any entry with given $post_id.

To avoid this possibility, you have two ways:

1st - Checking if $post isn't null before deleting

if ($post) {
    $post->delete();
}

**2nd - Using the firstOrFail() Eloquent method

$post = Post::where('id', $post_id)->firstOrFail();

This will internally call abort(404) if the model doesn't exists.

I've tried, but no success.

So the last possibility is that your $post_id is empty for some reason. Check your http request.

Upvotes: 1

Related Questions