cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
778 stars 109 forks source link

How to add condition on how data are to be sent over the API #597

Closed pro-cms closed 3 years ago

pro-cms commented 3 years ago

I have two tables, one is a Book table and another is a Book Payment table in the Book table I just store book info and amount for payment and in the Book Payment table I store ref_id , book_id, user_id, etc

Now I want to send a response depending on whether the user has paid for the book or not if the user paid then it sends 1 in the is_paid part of the response else it displays 0 that I know it is not paid. i am steel a beginner at this package

Anyone who can explain how to implement this

ben221199 commented 3 years ago

I think you should take a look at scopes: https://laravel-json-api.readthedocs.io/en/latest/fetching/filtering/#filter-scopes

lindyhopchris commented 3 years ago

Or this could be a filter? Not entirely sure where you are stuck! Is it in querying the database? Or to do with showing an is_paid attribute within the JSON:API resource?

pro-cms commented 3 years ago

I want to add is_paid in attribute part of response , if the user payment status of the book is success, is_paid return 1 otherwise 0.

lindyhopchris commented 3 years ago

So yeah, this is tricky because you're adding a virtual attribute that doesn't actually exist.

For this, I'd suggest using Eloquents withCount() feature to add a count to the Book model, using additional constraints to scope the query by the current user: https://laravel.com/docs/8.x/eloquent-relationships#counting-related-models

The only way to ensure that count column is added to every book model, regardless of whether the books are being retrieved via a /api/books request, or /api/books/1 request, or via an include path on a different request, is to use a global scope to add the withCount query: https://laravel.com/docs/8.x/eloquent#global-scopes

I'd use middleware to add the global scope.

pro-cms commented 3 years ago

Thanks so much @lindyhopchris i found my solution from you explanation