Delete row from db after certain condition has been meet in laravel

801 Views Asked by At

My table has data id post_id description and dispose_time. I wanted to delete data from DB if current time and date is greater than the current time.

 $post = Post::delete()->where('dispose_time' > DATE_SUB(NOW())), INTERVAL 10 MINUTE));

something like this . it is giving me the error and the dispose_time in my DB is in timestamp format something like this 1555107000 . Any Help appreciated.

3

There are 3 best solutions below

4
Surender Singh Rawat On BEST ANSWER

Use delete clause at last , like this:

Post::where("dispose_time", ">", now()->addMinutes(-10)->toDateTimeString())->delete();
6
Francinaldo Almeida On

Based on the information you provided, you should use the whereRaw method, and not where, since you are using SQL as where clause. Also, delete() should be the last method to be called. So your code would be the following:

Post::whereRaw("`dispose_time` > DATE_SUB(NOW(), INTERVAL 10 MINUTE)")->delete();

Since you are using Laravel, it comes with the Carbon package and you can also do the following

Post::whereDate('dispose_time', '>', Carbon\Carbon::now()->addMinutes(-10))->delete();
0
Imad Ullah On

Use Carbon for time in laravel.

$post = Post::where('dispose_time', '>', Carbon::now())->delete();