laraveleloquentpolymorphismpolymorphic-relationship

How to Delete or Destroy polymorphic relation laravel?


I am now trying to learn polymorphic type relations, but I have problems deleting the data
Is there a solution to solve the problem or some reference to solved this problem ?

Thank you

/**
     * Add Comment
     *
     * @param [type] $id
     * @return void
     */
    public function addCommentPost(Request $request, $id)
    {
        Post::find($id)->comments()->create([
            'body' => $request->get('comment'),
        ]);

        return redirect()->back();
    }

Solution

  • $posts->comments() is the relationship query to return all of the comments for a single post. If you call delete() on that, it will delete all of those records. If you only want to delete a specific record, you need to make sure you only call delete on the one you want to delete. For example:

    $posts->comments()->where('id', '=', 1)->delete();