To incorporate an Eloquent API resource with Spatie QueryBuilder, you can follow these steps:
- Create an Eloquent API resource for the
WorkHoursmodel. Let's call itWorkHoursResource. In this resource, you can define how theWorkHoursmodel should be transformed when returned as a JSON response. You can also perform any additional data manipulation or formatting.
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class WorkHoursResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'user_id' => $this->user_id,
// Add other attributes you want to include
'approved' => $this->approved ? 'Yes' : 'No',
// Perform any additional data manipulation or formatting
];
}
}
- Modify your code to use the
WorkHoursResourcewith Spatie QueryBuilder. Replace the'workHours'key in theInertia::rendermethod with the following code:
'workHours' => WorkHoursResource::collection(
QueryBuilder::for(WorkHours::class)
->where('user_id', $user->id)
->with('area')
->allowedIncludes(['area'])
->allowedSorts('date')
->defaultSort('-date')
->allowedFilters([
AllowedFilter::callback('year', function(Builder $query, $value) {
$thirdSaturdayPrevious = Carbon::parse('Third Saturday of April ' . $value-1)->toDateString();
$thirdSaturdayThis = Carbon::parse('Third Saturday of April ' . $value)->toDateString();
$query->whereBetween('date', [$thirdSaturdayPrevious, $thirdSaturdayThis]);
})
])
->paginate(20)
->withQueryString()
),
- Now, the
WorkHoursitems returned by the query will be transformed using theWorkHoursResource. You can customize the transformation logic in theWorkHoursResourceclass to match your requirements.
Note: Make sure to import the necessary classes at the top of your file:
use App\Http\Resources\WorkHoursResource;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
This solution uses the WorkHoursResource::collection() method to wrap the WorkHours items returned by the query. The collection() method applies the WorkHoursResource transformation to each item in the collection.