Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel where with Carbon addMinutes not working

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();
}
like image 355
user6122500 Avatar asked May 28 '17 11:05

user6122500


People also ask

How do you use Carbon function in Laravel?

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.

How do you add minutes to Carbon?

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.

Does Carbon come with Laravel?

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.


1 Answers

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)
    });
}
like image 160
Dov Benyomin Sohacheski Avatar answered Nov 15 '22 01:11

Dov Benyomin Sohacheski