Laravel-json-api: How to add condition on how data are to be sent over the API

Created on 29 Mar 2021  路  5Comments  路  Source: cloudcreativity/laravel-json-api

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

question

All 5 comments

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

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?

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.

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.

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

umbert-cobiro picture umbert-cobiro  路  4Comments

JeanLucEsser picture JeanLucEsser  路  6Comments

danherd picture danherd  路  7Comments

GregPeden picture GregPeden  路  5Comments

nelson6e65 picture nelson6e65  路  3Comments