Sidney Sousa
Sidney Sousa

Reputation: 3584

My schedule command deletes all my records

I have a table called offers and this is how I store in my controller:

$offer = Offer::Create([
    'user_id' => Auth::id(),
    'property_id' => $request->property_id,
    'offer_price' => $request->offer_price,
    'offer_period' => $request->offer_period,
    'offer_message' => $request->offer_message,
    'cash_amount' => $request->cash_amount,
    'buyer_type' => $request->buyer_type,
    'expires_at' => now()->addMinutes($request->offer_period),
]);

I want to delete all the offers where the expires_at is older than the updated_at date. I am using the timestamps.

This is what I have in my kernel:

$schedule->call(function () {

    Offer::where('updated_at', '>', 'expires_at' )->delete();

})->everyMinute();

When I ran the command:

php artisan schedule:run

I noticed that all the offers were deleted from my database. I ran the command at 11:22, and even the rows that were meant to expire at 11:30 were deleted.

Is there anything that I possibly did wrong?

Upvotes: 0

Views: 32

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

Instead of:

Offer::where('updated_at', '>', 'expires_at' )->delete();

you should use:

Offer::whereColumn('updated_at', '>', 'expires_at' )->delete();

Initially you used simple where. Laravel doesn't know that expires_at is here column name so where would be something like this:

SELECT * FROM offers where updated_at > 'expires_at'

And using second method Laravel will generate:

SELECT * FROM offers where updated_at > expires_at

without quotes (ant this is what you need here).

Instead of second method you can also use DB::raw construction like this:

Offer::where('updated_at', '>', \DB::raw('expires_at'))->delete();

Upvotes: 2

Related Questions