Query Scopes: manage them for queued Jobs, controller routes and relationships #51536
Replies: 1 comment 2 replies
-
Interesting suggestion. For queues we never serialize models but their ids and we query for them in the job. We did not see the usefulness of scopes. But now that you posted this and need to force the scope in the route (not like the optional query filter): list all (without scopes) with filters: list not deleted with filters: list deleted with filters: so in conclusion the scope could be introduced in route as a prefix. GET /{scope}/resource |
Beta Was this translation helpful? Give feedback.
-
Hey Laravel Community!
This is a bit of an idea, debate and open question. Recently we have implemented Query Scopes in our project. We manage Bookings for Rentals. We want certain type of booking Statuses to be out of all our queries, for instance, Cancelations or Requests to Book (not yet confirmed reservations). So we implemented the above mentioned query scopes.
Now, sometimes you have to do things with bookings which are oursie of the scope, like with canceled bookings. I may create a job to handle the things to do after canceling a reservation in the database. I pass this to a job in a queue and yeah, obviously it doesn't work. Why? Because Laravel serializes the model by id, and when retrieving back such model, uses the query scopes and canceled bookings are outside of the scope, thus the job fails. The solution I've found is to pass the id and we do our own query of the booking.
However, this is a recurring problem because happens exactly the same with controller routes with model binding and with relationships. In both cases, you are looking for a particular booking, regardless of it's state. So if I'm looking for the route /bookings/124, I'm looking for such booking even though it's canceled. If I'm within a booking payment and I'm looking to use the relationship to get the parent booking ($bookingPayment->booking), even though it's canceled, I wish to find it. Now both problems have solutions, but they are a bit outside of the Laravel standards and decrease maintainability. For routes it's nicer, I've implemented the resolveRouteBindingQuery() method inside the Laravel Model class, but for routes, I have to tell Laravel that all relationships pointing to booking must be without any query scope.
Now opening up the debate, should we add to Laravel something where you can define de behaviour of each Query Scope? Just as an idea, some methods to define the default behaviour for routes, relationships and jobs? For instance something like this:
Currently Laravel uses Scopes to handle Soft deletes. For routes we have a solution to query deleted models, but I think there is no solution to pass a soft deleted model to a Job. So would be useful for such cases as well.
Regards!
Beta Was this translation helpful? Give feedback.
All reactions