I'm building an API in Laravel 5.4, using Laravel Passport 3 for authentication. All of my API methods return a set of values that are always returned, success
, errors
(if there are any errors) etc.
I've changed the response of a \Illuminate\Auth\AuthenticationException
throws, to fit with the rest of my app, however I'm not sure how to change the response of various token grant responses, without doing something horrible like editing the vendor files.
I think you can use middleware to change your response.
From laravel documentation:
Before & After Middleware
Whether a middleware runs before or after a request depends on the middleware itself.
You can capture the response and re-format the response.
You can use laravel's setContent
method to set the content in response. Check here.
What you are trying to do here is not supported by the library, so whatever you do will be hacky and will probably break the compatibility with future versions of laravel/passport
.
In my opinion, you can only choose between those 2 options:
Instead of declaring passport routes (Passport::routes()
) you can declare equivalent routes to your custom methods. Those method internally calls Passport classes and methods, handling passport returning values before returning them to the user. It requires a lot of digging into passport code but, at the same time, if you only add some fields (success
or error
) you should be able to update your code without too much effort when updating the library.
Fork laravel/passport
and modify it to suit you needs. This solution in not as messy as the first, but a merge with new versions of passport in the future will probably be hard.
Of course, both are not great solutions. Keeping the standard passport responses or use a more suitable library are better options: I assume they are not feasible if you are asking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With