Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple row from DB table by laravel?

Tags:

php

laravel-5

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();
    }

like image 899
R.H.Prem Avatar asked Oct 24 '25 19:10

R.H.Prem


1 Answers

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

like image 138
Evgeniy Maynagashev Avatar answered Oct 26 '25 10:10

Evgeniy Maynagashev