Home > Back-end >  Laravel request remove fields before validation
Laravel request remove fields before validation

Time:05-25

I am trying to remove some fields before they are validated.
Trying to attempt this inside prepareForValidation()

    protected function prepareForValidation()
    {
        $video_id = $this->route('video_id');
        if($this->isMethod('put') && Video::salesStarted($video_id)){
            Log::info('removing sales');
            //$this->safe()->except(['sales_start', 'tickets', 'price']);
            $this->request->remove('sales_start');
            $this->request->remove('tickets');
            $this->request->remove('price');
        }
        if($this->isMethod('put') && Video::streamStarted($video_id)){
            Log::info('removing streams');
            //$this->safe()->except(['stream_start', 'stream_count', 'archive']);
            $this->request->remove('stream_start');
            $this->request->remove('stream_count');
            $this->request->remove('archive');
        }
    }

I made sure the code was entering inside the if statement, however the fields are not being removed.

Running $this->request->remove() and $this->except() have no effect.
If I add safe() it throws Call to a member function safe() on null.
I also tried to use unset() but nothing seems to work.

The rules for the dates are like so:

'sales_start' => 'sometimes|required|date|after:now|before:stream_start',
'stream_start' => 'sometimes|required|date|after:now',

but the $request->validated() returns the errors although it shouldn't be validating the deleted fields.

"sales_start": [
    "The sales start must be a date after now."
],
"stream_start": [
    "The stream start must be a date after now."
]

Why are the fields not being deleted?

CodePudding user response:

Can't find anything about deleting. But acording to Laravel docs you pick what keys you need from a request as follows:

$request->only(['username', 'password']);
// plug everything you need into the array.
$request->except(['username', 'password']);
//plug everything you don't need into the array

The latter is probably most useful to you.

Example:

Say I have the following keys: ['username', 'password', 'randomVal'];

$request->only(['username', 'password']);
// Output:
['username', 'password']

$request->except(['username', 'password']);
// Output:
['randomVal']

CodePudding user response:

To remove (unset) a key from a Request before it goes to the Controller you can use offsetUnset()
inside your request:

 protected function prepareForValidation()
    {
        $this->offsetUnset('sales_start');//same goes for the other key to remove...
    }
  • Related