burtonLowel
burtonLowel

Reputation: 794

Laravel: How to handle optional data in a form request?

I have a blade that under certain conditions shows Form1 and other conditions will show Form2. In Form1, the only field available is description and that is what is getting updated. In Form2, the message field is the only one available and that is what gets edited.
How would I handle this in the Form request file? I was think of making them nullable like this:

return [
    'message'       => 'nullable',
    'description'   => 'nullable'
];

But I want the description field to be required when Form1 is used and message to be required when Form2 is used.

Upvotes: 0

Views: 522

Answers (1)

Pavel Lint
Pavel Lint

Reputation: 3527

You could use conditional validation in your controller, similar to this:

   if( form 1 is sumbitted ) {
     $validatedData = $request->validate([
        'message' => 'required|string'
    ]);
   }
   elseif( form 2 is submitted ) {
     $validatedData = $request->validate([
        'description' => 'required|string'
    ]);
   }

Upvotes: 1

Related Questions