Leff7's avatar
Level 4

Laravel validation rules if field empty another field required

I have a Laravel 5.3 app, and an update form where I send user profile values. One of them is user image as well, I am creating a hidden input field for it, so if the user is not uploading any new image, I can still see that he has the hidden field with the old image value.

<input type="hidden" class="form-control" name="old_image" value="{{ $player->image_filename }}" id="oldImage">

If he removes the image, the hidden input value becomes empty.

document.getElementById('oldImage').value = '';

That is how I thought of updating a user image. But I don't know how to set up validation rules for that form. Something that would be similar to this:

    public function rules()
    {
        return [
          'first_name' => 'required|max:50',
          'last_name' => 'required|max:50',
          'birthday' => 'required',
          'image' => required if old_image empty
        ];
    }
0 likes
7 replies
Leff7's avatar
Level 4

I tried this: 'image' => 'required_if:old_image, ""',but didn't get any error message for it.

RonB1985's avatar
RonB1985
Best Answer
Level 18
   'old_image'  => 'required_without:new_image',
   'new_image'  => 'required_without:old_image',

Like this, the old_image is required when the new_image is empty. And the new_image is required when the old_image is empty.

7 likes
RonB1985's avatar

You mean, no error message is displayed when you leave BOTH old_image AND new_image empty? Because if you have one or both not empty, then that means it's working as intended.

Leff7's avatar
Level 4

sorry, it is working as it should, error message wasn't displaying for other reason, in the view I had some if statement that didn't allow error message to show. Thank you for your help!

1 like

Please or to participate in this conversation.