0

I hope the question title already answers the subject here. Lets say I have a number of ids that needs to be validated in a request.

Example:

request uri: [POST] /album/{album_id}/song

Request payload:

[
  "song_title": "hello world",
  "genre_id": 2,
  "artist_id": [100, 102],
  "lyrics_by_id": 201
]

Now, as we know we would definitely have to validate those ids, for which we run some queries over there.

Is there a way out, where we can use those objects or data retrieved from database in order to use it in the rest of the code?

1 Answer 1

0

I found a solution by doing it in this way. Don't know if it is a best practice or not.

Merging it as a request payload, in the middleware if required in a lot of places. May be it could have been done in the service provider.

Example (In Laravel):

public function handle(Request $request, Closure $next){

    $genre = Genre::findOrFail($request->get('genre_id');
    $request->add('genre', $genre);

    return $next($request);

}
1
  • 1
    The PSR-7 (php-fig.org/psr/psr-7) defines the ServerRequestInterface which has a withAttribute($name, $value) method. There it is mentioned that "The request attributes may be used to allow injection of any parameters derived from the request". You can use a middleware that retrieves the objects from the database and add them to the requests attributes. I wouldn't do that in a service provider since they are used to register services to your application and not to transform/process data on every request.
    – VaaChar
    Nov 5, 2018 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.