Laravel where with Carbon addMinutes not working
Asked Answered
H

1

7

I have a table representing events, each of which has a notice period, e.g. you can't book the event if it's currently less than 24 hours before the event.

I'm trying to create a 'bookable' scope for this, but am failing. Specifically, in the below, 'time' represents the time of the event (timestamp), and 'notice' the notice period, in minutes (integer), both of which are columns in the Events model. What I've found is that Laravel is not reading the 'notice' variable, i.e. treating it as 0. Any guidance would be appreciated, thanks.

public function scopeBookable($q) {
    $q->where('time','>',Carbon::now()->addMinutes('notice'))->orderBy('time','ASC')->get();
}
Hulky answered 28/5, 2017 at 11:51 Comment(0)
M
18

The addMinutes() method expects an integer not a string.

Scope Option

You can pass the notice time through to the scope.

// Controller
$notice = 60;
Events::bookable($notice);

// Model
public function scopeBookable($q, $notice=0) {
    $q->where('time','>',Carbon::now()->addMinutes($notice))->orderBy('time','ASC')-get();
}

Collection Option

You can always execute a self-join in SQL and check the value of notice in a subquery. Another option is to return a filtered eloquent collection.

public function scopeBookable() {
    return Events::all()->filter(function($event) {
        return $event->time > Carbon::now()->addMinutes($event->notice)
    });
}
Midian answered 28/5, 2017 at 11:55 Comment(3)
The 'notice' column is indeed an integer. E.g. If I use addMinutes elsewhere with 'notice' it works, it's just for some reason when it's part of the queryScope it doesn't pick up the 'notice' variable properly.Hulky
@Hulky that might be, but Cabon does not know anything about your DB columns.Midian
Thanks. But 'notice' is a variable that actually varies by event. E.g. event A might have 10 minutes of notice, event B might have 60 minutes. How can we accommodate that? (it seems to me that within the query scope, once the 'notice' in the where clause is wrapped in a function it no longer gets recognised correctly)Hulky

© 2022 - 2024 — McMap. All rights reserved.