Lovelock
Lovelock

Reputation: 8105

Laravel Eloquent - where created_at is X days ago

I have an array of days that I want to check against for trials ending in Laravel Spark:

$trialIntervals = [10, 5, 3, 1, 0];

I fetch all teams and then check if their trial_ends_at date one of the intervals using diffInDays:

$daysTillTrialEnds = Carbon::parse($team->trial_ends_at)->diffInDays(Carbon::now());

I then check if this value is already an existing result in the database and in the intervals:

if ( in_array($daysTillTrialEnds, $trialIntervals) && !TrialEndingNotification::where('team_id', $team->id)->where('days_notified_at', $daysTillTrialEnds)->count() ) {

   // not yet been added to db

}

I have a field called 'days_notified_at' that I am using the check if I have already added the row and notified the customer. However that field is never used again and I would rather reference the created_at date and remove the field.

My question is how I essentially do this:

->where(Carbon::parse('created_at')->diffInDays(Carbon::now()), $daysTillTrialEnds)

Without getting this error:

DateTime::__construct(): Failed to parse time string (created_at) at position 0 (c): The timezone could not be found in the database

The aim is that the where will only show rows that have a created_at date that is X days ago.

Upvotes: 5

Views: 14917

Answers (5)

Hossin Asaadi
Hossin Asaadi

Reputation: 405

you can create scope in model like this :

public function scopeActive($query)
{
    return $query->whereDate('created_at' , '=', Carbon::today()->subDays( 2 ));

}

after that call scope in controller :

    $post = Post::active()->get();

Upvotes: 1

LorenzoBerti
LorenzoBerti

Reputation: 6974

Have you tried something like:

$dayAgo = 6 // where here there is your calculation for now How many days
$dayToCheck = Carbon::now()->subDays($dayAgo);
$model->whereDate("created_at", =, $dayToCheck);

Upvotes: 0

ATechGuy
ATechGuy

Reputation: 1270

Laravel will automatically turn the "created_at" into a carbon object so you don't have to parse it.

`$items->where('created_at')->diffInDays(Carbon::now(), $daysTillTrialEnds)'

Should work for you

Upvotes: 0

Vipin Kumar
Vipin Kumar

Reputation: 43

->where(Carbon::parse('created_at')->diffInDays(Carbon::now()), $daysTillTrialEnds)

to should be like

->where(Carbon::parse($item->created_at)->diffInDays(Carbon::now()), $daysTillTrialEnds)

Upvotes: 1

Walter
Walter

Reputation: 81

Use WhereRaw

->whereRaw('DATEDIFF(CURDATE(),STR_TO_DATE(created_at, '%Y-%m-%d'))'), $daysTillTrialEnds)

Upvotes: 1

Related Questions