Laravel: form validation is not working properly

When I try to use form validation to validate data from clients, I cannot validate it correctly because the method authorize()is executed even if the validation rules contained in rules()are violated.

This is the code:

class PostAssignRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $params = $this->request->all();

        if(User::find($params['userId'])->company != Auth::user()->company)
        {
            return false;
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'userId' => 'required|exists:users,id',
            'taskId' => 'required|exists:tasks,id'
        ];

        return $rules;
    }
}

This example User::find()runs even if the parameter is userIdnot set.

I also noticed that if the method authorize()just returns true, then I get a response 422telling me that the parameter is userIdmissing.

How should I deal with this? First, I would like to check the rules, and then, if they are ok, log in.

+4
source share
3

ValidatesWhenResolvedTrait@validate:

public function validate()
{
    $instance = $this->getValidatorInstance();

    if ( ! $this->passesAuthorization())
    {
        $this->failedAuthorization();
    }
    elseif ( ! $instance->passes())
    {
        $this->failedValidation($instance);
    }
}

, validate . , App\Http\Requests\Request:

public function validate()
{
    $instance = $this->getValidatorInstance();

    if ( ! $instance->passes())
    {
        $this->failedValidation($instance);
    }
    elseif ( ! $this->passesAuthorization())
    {
        $this->failedAuthorization();
    }
}
+3

Laravel (), . , , , .

422, Ajax. 422 .

+1

Middleware . . .

if(User::find($params['userId'])->company != Auth::user()->company)
{
  return false;
}
0

Source: https://habr.com/ru/post/1584911/


All Articles