Support the ongoing development of Laravel.io →
posted 5 years ago
Last updated 1 year ago.
0

there's several ways to do this. Here I pick one that I think the fastest to write.

assuming the dates key name is start and end in the form, then in your controller:

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
...

//your controller
class Controller extends BaseController
{
    use ValidatesRequests;


    //your controller function
    public function doSomething(Request $request){

        //create custom - Closure rule
        $sixDayAfter = function ($attribute, $value, $fail) use ($request) {

            //create Carbon instance of actual & expected end date
            $actualEndDate = Carbon::make($value);
            $expectedEndDate = Carbon::make($request->start)->addDays(6);

            //compare the dates. if they're different, validation fails
            if ( ! $actualEndDate->isSameDay($expectedEndDate)) {
                
                $fail('the end date should be 6 days after the start date ');
                //or whatever error message you want
            }
        };

        //do the validation
        $this->validate($request, [
            'start' => 'required',
            'end' => $sixDayAfter
        ]);

        //the dates ok, continue...
        ...
    }
}

further reference:

Hope it helps

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.