Laravel where with Carbon addMinutes not working

29,442

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)
    });
}
Share:
29,442
user6122500
Author by

user6122500

Updated on July 09, 2022

Comments

  • user6122500
    user6122500 almost 2 years

    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();
    }
    
  • user6122500
    user6122500 almost 7 years
    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.
  • Dov Benyomin Sohacheski
    Dov Benyomin Sohacheski almost 7 years
    @user6122500 that might be, but Cabon does not know anything about your DB columns.
  • user6122500
    user6122500 almost 7 years
    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)