Last active
May 25, 2021 17:26
-
-
Save troccoli/3cc8bc4dfd80a7c1c8e2d77eff2961a2 to your computer and use it in GitHub Desktop.
DayOfTheWeek Laravel Validation Rule
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Rules\DayOfTheWeek; | |
use Carbon\Carbon; | |
use Illuminate\Http\Request; | |
use Illuminate\Http\Response; | |
class DoSomethingController extends Controller | |
{ | |
// ... | |
public function store(Request $request): Response | |
{ | |
$validated = $request->validate([ | |
'date' => ['required', 'date', new DayOfTheWeek(Carbon::SUNDAY)], | |
]); | |
// ... | |
} | |
// ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Rules; | |
use Carbon\Carbon; | |
use Illuminate\Contracts\Validation\Rule; | |
class DayOfTheWeek implements Rule | |
{ | |
public function __construct(private int $dayOfTheWeek) | |
{ | |
$this->weekDay = Carbon::now()->setDay($this->dayOfTheWeek)->englishDayOfWeek; | |
} | |
/** | |
* @param string $attribute | |
* @param mixed $value | |
*/ | |
public function passes($attribute, $value): bool | |
{ | |
return Carbon::parse($value)->dayOfWeek === $this->dayOfTheWeek; | |
} | |
public function message(): string | |
{ | |
return "The :attribute must be a ".Carbon::getDays()[$this->dayOfTheWeek]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment