简体   繁体   中英

how to validate the hour that is being booked?

id start_date end_date
1 2022-10-10 11:00:00 2022-10-10 15:00:00

I have a data row in the booking table as above, I want when there is input start_date: 2022-10-10 12:00:00 or 2022-10-10 13:00:00 or 2022-10-10 14:00:00 , because at that time it was still in the booking range like the example table above,

How do I validate it so that the user cannot add the time that is included in the booking range?

This should point you in the right direction.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BookingController extends Controller
{
    function book(Request $request)
    {
        $request->validate([
            "booking_start_date" => [
                "required",
                "date_format:Y-m-d H:i:s",

                function ($attribute, $value, $fail) use ($request) {

                    $booking = \App\Models\Booking::where([
                        ["start_date", "<=", $request->booking_start_date],
                        ["end_date", ">=", $request->booking_start_date],
                    ])->orWhere([
                        ["start_date", "<=", $request->booking_end_date],
                        ["end_date", ">=", $request->booking_end_date],
                    ])->first();

                    if ($booking) {
                        $fail(
                            sprintf("An appointment between '%s' and '%s' has already been booked. Please, try booking again outside this range.",
                                \Carbon\Carbon::create($booking->start_date)->format("d M Y H:i"),
                                \Carbon\Carbon::create($booking->end_date)->format("d M Y H:i")
                            )
                        );
                    }

                },
            ],

            "booking_end_date" => [
                "required",
                "date_format:Y-m-d H:i:s",
                "after:booking_start_date",
            ],

        ]);
        
        // Create/insert new data below this line of code.
        $newBooking = \App\Models\Booking::create([
            "start_date" => $request->booking_start_date,
            "end_date" => $request->booking_end_date,
        ]);

        return response()->json($newBooking);

    }
}

Using Closures

If you only need the functionality of a custom rule once throughout your application, you may use a closure instead of a rule object. The closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails:

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