V
V
vrazbros2019-11-17 11:11:28
Laravel
vrazbros, 2019-11-17 11:11:28

How to check request parameters in Laravel?

Hi
I ran into a problem that is not clear to me, I can’t check for the presence of the user id in the request, I delete the user from the Route group
:

Route::prefix('group')->group(function () {
      Route::delete('{user_id}/user', '[email protected]');        
});

Request
class UserRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'user_id' => ['int', 'required'],
        ];
    }
}

Controller
public function removeUser(UserRequest $request): SuccessResponse
{
    echo "tets";
}

url test.lcom/group/12/user
the request is sent by the http method delete
gives an error: user_id field is required as I understand it, the request validation rules do not pass,
Why does the request validator not see the user_id value for which they are sent in the url?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin B., 2019-11-17
@Kostik_1993

UserRequest is your class that inherits from FormRequest, the keyword here is Form - it means that you are checking what was sent from the form.
As for your case, the findOrFail method is used here, this method is the same find () method, but only if there is no such entry in the table, a 404 error will be returned

public function removeUser($userId)
{
       $user = User::findOrFail($userId);
       $user->delete();
}

A
Alex Wells, 2019-11-17
@Alex_Wells

Because that's how FormRequest works. You can add this to your base request form if you need it:

/**
   * {@inheritdoc}
   */
  public function validationData(): array
  {
    return array_merge(
      $this->all(),
      $this->routeParameters()
    );
  }

  /**
   * Get route parameters for this request and wrap them into {} each.
   *
   * @return array
   */
  protected function routeParameters(): array
  {
    return collect($this->route()->parameters)
      ->mapWithKeys(static function ($item, $key) {
        return ['{'.$key.'}' => $item];
      })
      ->toArray();
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question