I'm building a simple booking system in Laravel which is used by both admins and normal users.
In my BookingController.php is have an index method to fetch all bookings.
public function index(Request $request): Response
{
$limit = ($request->has('limit')) ? $request->get('limit') : 20;
$bookings = $this->booking
->pushCriteria(new BelongsToTeam())
->pushCriteria(new RequestWith())
->pushCriteria(new ModelFilter())
->orderBy('date')
->paginate($limit);
return Inertia::render('Bookings/Index', [
'filteredDate' => ($request->date && $request->date != '') ? $request->date : Carbon::now()->format('Y-m-d'),
'filteredCalendar' => ($request->calendar && $request->calendar != '') ? $request->calendar : '',
'bookings' => new BookingCollection($bookings)
]);
}
The important bit here is
->pushCriteria(new BelongsToTeam())
This bit of code works fine for an admin when we want to return all the bookings that belong to this users team. I do, however, also want to use this controller method for normal users logging in to fetch all the bookings that belong to this user. This would obviously alter the database query I write to fetch the bookings based on the role that the logged in user has.
My question is, what pattern can I use to ensure that I avoid writing unnecessary if statements to determine how I fetch my bookings from the database?
Aucun commentaire:
Enregistrer un commentaire