4

I want to delete all comments from comments table.I did that by doing this but this is not the laravel way. Anyone answer the correct steps please .

$comments = Comment::where('post_id',$id)->get();
    if(count($comments)>1)
    {
        $comment_id= [];
        foreach ($comments as $i)
        {
            $comment_id[] = $i->id;
        }
        for($i=0;$i<count($comments);$i++)
        {
            Comment::find($comment_id[$i])->delete();
        }
    }
    elseif (count($comments)==1)
    {
        $comments->delete();
    }

1
  • Please scepicify the name of the fields. and the 'Something by Laravel in destroy method' Commented Jan 9, 2017 at 1:06

4 Answers 4

24

Since each Eloquent model serves as a query builder, try this, all in one line:

Comment::where('post_id',$id)->delete();

Tested in tinker, works as expected, returns count of deleted rows.

Documentation: https://laravel.com/docs/5.3/queries#deletes

Sign up to request clarification or add additional context in comments.

Comments

3
DB::table('users')->whereIn('id', $ids_to_delete)->delete(); 

or

$org-products()->whereIn('id', $ids)->delete();

1 Comment

Please add some comments about your code and how does it answers the question.
2

You can try the following approach:

public function deleteAll(Request $request)
{
    $ids = $request->ids;
    Comment::whereIn('id',explode(",",$ids))->delete();
}

Comments

0

Collect only ids from your command like below and destroy by model.

$yourRaws = YourModel::where('name', 'Enver')->get();
...
YourModel::destroy($yourRaws->pluck('id')->toArray());

Enjoy Your Coding !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.