Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

arshver's avatar

Delete post automatically by date

I've added an additional field for my post I want to delete posts from the database when the expiration date is equal to today's date I wrote the following Is that okay?

        $namess=Post::where('Expiration_date','=',Carbon::now())->delete();
        $namess=Post::where('user_id', auth()->user()->id)->paginate(4);
        return view('user.post.maneger',compact('namess'));
0 likes
3 replies
Snapey's avatar

You would usually put this functionality in its own method so that you can call it from the scheduler - not as part of a user request.

Suppose you have a post due for removal tomorrow, but you get no visitors tomorrow. The post that should be expired is missed and never gets deleted because the date never matches

Also, why would you run this query on every user visit when it only needs to be run once per day?

Depending on the column type, you might currently need to match the time exactly also.

To resolve some of these, change your query slightly;

Post::where('Expiration_date','<',Carbon::now())->delete();

You don't need the return value and you can check if the date is less than the current date rather than equal to.

pardeepkumar's avatar

This is correct by

 Schema::table('flights', function ($table) {
    $table->softDeletes();
});

Soft Deleting

In addition to actually removing records from your database, Eloquent can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at .

more information : https://laravel.com/docs/5.6/eloquent

Please or to participate in this conversation.