简体   繁体   中英

Laravel 5.4 query check if value exists between the keys/values of an array

I'm using Laravel 5.4 and this is my use case:

I have a list of Lessons , every Lesson is associated with a specific User and has a date , star_at and end_at fields. In the form that allows me to add/edit Lessons I need to do a validation check ( we choose the date, start and end in the form ): - The new Lesson shouldn't be in the time range ( start_at -> end_at ) of another Lesson during the selected date .

So I did a query to retrieve all the Lessons ( as an array of key(start_at) & value(end_at) ) of the current User where date = the selected date in the form.

Now I need to check if the start_at value that we've chosen in the form exists in the time range of any of the retrieved Lessons array records. and maybe then display the error ( There is already a Lesson in this time range at this date ).

Please help, it can be a bit unclear, but I can explain further if you need.

Thank you in advance.

Based on my understanding of the question, the below code should do the trick. Change the model and field names based on your application.

protected function store()
{
    $input = request()->all();

    $lessons = Lesson::whereDate('date', Carbon::parse($input['date']))
        ->where('start_at', '>=', Carbon::parse($input['start_at']))
        ->where('end_at', '<=', Carbon::parse($input['start_at']))
        ->count();

    if ($lessons) {
        // lesson in exists on this date in the given time frame.
        // handle error
    }

    Lesson::create($input);

    // handle success
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM