Laravel: Validate Fields Only When One Is Present

Sometimes, when setting up validation for Laravel forms, you need to be able to set up validation rules for two fields, but allow for one of them to be ignored if the other is filled. This is how you can set up your validation rules to make that happen:

'email' => 'nullable|required_without:login',
'login' => 'nullable|required_without:email'

You first have to set nullable to allow both fields to have null values, otherwise Laravel rejects them. After that, you set each field to require_without:[otherField]

A potential use case for this (and the one I needed it for) is when your application allows a user to login using an email, a login, or both. It turns out sometimes didn’t work at all for this because it only applies when the field in question sometimes isn’t sent, not cases where it is sent but the value is null. The solution above accounts for this.

Laravel and PHPUnit Error: Supported Ciphers

While setting up unit testing for a PHP project, I ran into this error when I first tried to run the simple example tests to prove the system was set up correctly:

RuntimeException: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.

Searching for this error revealed that, by far, this issue most commonly happened when you had an improper app key, and the solution was simply to regenerate the key — but this was not my problem, because I had a perfectly valid app key. I even regenerated it for good measure, and still I got the error. Nothing else on the first two pages of Google provided any help for my situation, and once I started getting the foreign-language pages I knew I was on my own.

Fortunately, in this case, the solution proved to be simple. In the phpunit.xml file Laravel automatically generates, I found this in the section for setting up environment variables:

<env name="APP_ENV" value="testing"/>

Aha! It was set to look for the testing environment, aka .env.testing! Sure enough, my environment file had the application key set to, literally, the word “key”. I simply copied over my main .env file into .env.testing, ensuring the correct key value was provided, and this solved the issue.