Search code examples
phpjsonlaravellaravel-5laravel-validation

Validate Parameters as a JSON String in Laravel


Front End Part

The parameters are being sent like this:

Front End sending data

Laravel Request

class CarCreateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        //TODO: Define authorization logic, possibly a middleware
        return true;
    }  

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'car.name' => 'present|required'
        ];
    }
}

Real Problem

The request class always validates to false. I checked the Validating Array section, but it looks like this works sending parameters like this:

car[name]=Spidey Mobile

However, I need to send this data stringified using JSON.stringify().

Is there a workaround for this? It looks like dot notation isn't working since this is a JSON string rather than an array. I've tried modifying the request data before being evaluated, but I haven't found anything that works for Laravel 5.7.


Solution

  • Here's the solution, I used both the sanitize and validator method within the request in order to change the request data before being evaluated.

    class CarCreateRequest extends FormRequest
    {
        /**
        * Determine if the user is authorized to make this request.
        *
        * @return bool
        */
        public function authorize()
        {
            //TODO: Define authorization logic, possibly a middleware
            return true;
        }  
    
        public function validator($factory)
        {
        return $factory->make(
            $this->sanitize(), $this->container->call([$this, 'rules']), $this->messages()
        );
        }
    
        public function sanitize()
        {
            $this->merge([
                'car' => json_decode($this->input('car'), true)
            ]);
            return $this->all();
        }
    
        /**
        * Get the validation rules that apply to the request.
        *
        * @return array
        */
        public function rules()
        {
            return [
                'car.name' => 'present|required'
            ];
        }
    }
    

    The json_decode will transform the JSON string into an array that can be validated by Laravel.