Skip to content

Instantly share code, notes, and snippets.

@troccoli
Last active May 25, 2021 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troccoli/3cc8bc4dfd80a7c1c8e2d77eff2961a2 to your computer and use it in GitHub Desktop.
Save troccoli/3cc8bc4dfd80a7c1c8e2d77eff2961a2 to your computer and use it in GitHub Desktop.
DayOfTheWeek Laravel Validation Rule
<?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)],
]);
// ...
}
// ...
}
<?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