简体   繁体   中英

laravel validator for rest api

I am trying to follow best practice for REST api on CRUD.

GET: users/ -> all
GET: users/:id -> one specific user.
POST: users/  -> add one
PUT: users/:id -> update specific user.
DELETE: users/:id -> delete one user.

On laravel 8 I want to validate the url :id using the validator, so I have like this on delete user:

$validator = Validator::make(['id' => $request->id], [
    'id' => 'exists:users,id,deleted_at,NULL',
]);

And this way to update a user:

$validator = Validator::make(array_merge($request->all(), ['id' => $request->id]), [
    'id' => 'required|exists:users,id,deleted_at,NULL',
    'name' => 'required',
    'surname' => 'required',
    'email' => 'required|email:rfc,dns'
]);

As you can see I have to put the id on an array and/or merge with the $request->all() . There is any way in laravel to do this with the request?

I have found 3 ways by Laravel:

$request->add(['variable' => 'value']);
$request->merge(["key"=>"value"]);
$request->request->set(key, value);

But a solution for adding route params to the request before hitting the controller method would be even great.

You can update the request object on the fly and add the ID field, before you validate it, something like

$request['id'] = $id;
// note: the $id is your function's parameter name

$validator = Validator::make(array_merge($request->all()), [
    'id' => 'required|exists:users,id,deleted_at,NULL',
    'name' => 'required',
    'surname' => 'required',
    'email' => 'required|email:rfc,dns'
]);

You can do it like you are doing, but doing it with route model binding would be the way to go.

Now when you want to update a user by sending a PUT to /users/:id , and the user does not exist you will get a 422 . But what you really want would be a 404 .

With route model binding, Laravel will check if the model exists for you and abort with a 404 when it does not.

If route model binding is not an option, you can also just not validate the id with the validator and retrieve the user with User::findOrFail($request->input('id')) , the framework will then still abort with a 404 if it can't be found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM