Validating Enumerations in Laravel

Home Blogs
Validating Enumerations in Laravel

In our previous blog post, PHP 8.1 Enumerations and Laravel, we discussed how enumerations can enhance the strictness of your application.

Laravel enables easy validation of user input against enumerations. Continuing with the example of Order Statuses, let's explore this feature further.

If you have an order detail page and you want to give the user an option to change the Order Status, you could provide them with a select list of options.


	<select name="status">
		@foreach(App\Enums\OrderStatus::cases() as $orderStatus)
			<option value="{{ $orderStatus->value }}">{{ $orderStatus->name }}</option>
		@endforeach
	</select>

Once the form is submitted, it is essential to validate the data to ensure data integrity. Thankfully, Laravel provides a convenient validation rule for this purpose. In your form request, you can define a new rule that checks the validity of the submitted value.


	<?php

	namespace App\Http\Requests;

	use App\Enums\OrderStatus;
	use Illuminate\Foundation\Http\FormRequest;
	use Illuminate\Validation\Rules\Enum;

	class OrderFormRequest extends FormRequest
	{
		public function rules(): array
		{
			return [
				'status' => [new Enum(OrderStatus::class)].
			];
		}
	}

By adding this rule, you guarantee that the supplied value corresponds to a valid case in the Order Status enumeration. Simple as that!