0
votes

I have a Laravel application and am using the Form Request validation.

I have implemented the following:

 public function rules(){
      return [
            'item_name'=>'required',
            'item_description'=> 'required',
        ];
    }

In the controller I have the following:

public function storeItem(storeItem $request) {
        $validated = $request->validated();
         ...
         ...     

        }
    }

This works correctly, but because for certain items not all $request variables are required, I would like to implement a switch statement as follows:

public function rules()
{
    $item_type = $this->route('item_type');
    switch($item_type) {
        case 'type1':
             return [
                'item_name'=>'required',
                'item_description'=> 'required',
            ];
            break;
         case 'type2':
             return [
                'item_name'=>'required',
                'item_amount'=> 'required',
                'item_favorite'=> 'required',
            ];
            break;
    }
}

I'm getting back the following error:

Argument 2 passed to Illuminate\Validation\Factory::make() must be of the type array, null given

This error message seems to suggest I'm not returning an array, but I do have the return statements per switch case so not sure why I see this eeror message.

Any idea how this could be solved? If a switch statement is not the good option, any other idea?

1
$request of type storeItem ? - nice_dev
Yes, documebted here (laravel.com/docs/5.7/validation#form-request-validation). It mentions "All you need to do is type-hint the request on your controller method". That part is working fine. It's the Switch statement that causes issues - wiwa1978
Fair enough. Your switch case itself has the string 'item_type'. You probably want to pass a variable there, else it won't match with any case and defaults to nothing. - nice_dev
That was a left over still, I edited the original post. Issue still exists - wiwa1978
Thanks for the suggestion - wiwa1978

1 Answers

0
votes

Here is the solution:

public function rules()
{
    switch($this->request->get('item_type')) {
        case 'Type1':
             return [
              'item_name'=>'required',
              'item_description'=> 'required',
            ];
            break;
         case 'Type2':
             return [
                 'item_name'=>'required',
                 'item_amount'=> 'required',
                 'item_favorite'=> 'required',
            ];
            break;

        default:
            return [
                'item_name'=>'required',
            ];
    }
}