Home > Software design >  Get user's id and request info in Validation
Get user's id and request info in Validation

Time:09-16

I created FormRequest file to validate some requests in Laravel

class NewPostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    protected function failedValidation(Validator $validator) {
        Log::error($validator->failed());
        return responder()->error()->respond(400);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'post' => 'present',
            'type' => 'required|string|in:text,image,video',
        ];
    }
}

I sometimes get an error log like that

array (
 'post' =>
 array (
   'Present' =>
   array (
   ),
 ),
 'type' =>
 array (
   'Required' =>
   array (
   ),
 ),
)

My question is how can I get the log of current user's ID which is making the request and the request info such as post and type when failedValidation triggered?

CodePudding user response:

protected function failedValidation(Validator $validator)
{
    $data = [
        'user' => auth()->user(),
        'type' => request()->method()
    ];
    // your code ........

}

CodePudding user response:

Log::error([
    'failedValidation' => $validator->failed(),
    'userId' => auth()->user()->id,
    'failedFieldValues' => $this->all(array_keys($validator->failed()))
    'submittedPayload' => $this->all()
]);
  • Related