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();
}
Example-1: Read the current date and time The simplest use of the Carbon class is to read the current date and time. Open the datetimeController. php file and replace the content with the following script. The now() function of the Carbon class has been used in the script to read the current date and time.
Using the carbon addMinute() or addMinutes() function you can change the minutes in the date in laravel 8. If we need to add minute or more then one minutes in date and time then you can use carbon in laravel. carbon provides addMinute() and addMinutes() method to add minutes on carbon date object.
Setting Up the Project. In order to use Carbon, you'll need to import Carbon from the Carbon namespace. Luckily for us, Carbon is already included in Laravel.
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)
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With