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();
}
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)
});
}