Only Owner Can Delete The Post

How to allow the owner (creator of the post) to delete the post? Only the owner can delete the posts in laravel.

How to check the owner and allow them to delete the post?

How to use the if statement to check if it is the owner who is trying to delete the post?

How to use the if statement in the controller to delete or otherwise redirect to unauthorized (401 error)?

How To Delete Comments Along With Thread?

Code

Here we can use the if statement before the delete action is done.

We can easily use auth() or Auth::user() to check the authentication. It shows the auth user details and works when the user is logged-in.

So, we will place this in the if statement.

If auth user is equal to the post->user_id, then do this.

if(auth()->user()->id == $thread->user_id){
     $thread->delete();
}
else
{
     abort(401, "unauthorized");
}

Or,

If auth user is not equal to post->user_id, then do this.

        if(auth()->user()->id !== $thread->user_id){
            abort(401, "unauthorized");
        }

Full function to delete a post by checking the owner of the post. It will show 401 unauthorized error page if the logged user id is not equal to the user id of the post.

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Thread  $thread
     * @return \Illuminate\Http\Response
     */
    public function destroy(Thread $thread)
    {
        if(auth()->user()->id !== $thread->user_id){
            abort(401, "unauthorized");
        }
        $thread->delete();

        return redirect()->route('thread.index')->withMessage('Thread has deleted successfully !');
    }

Related Posts