Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide examples of how Spatie integrates with Laravel's Eloquent ORM


Can you provide examples of how Spatie integrates with Laravel's Eloquent ORM


Spatie integrates with Laravel's Eloquent ORM primarily through its Laravel Query Builder package, which extends Eloquent's query capabilities to handle complex filtering, sorting, including relationships, and selecting fields directly from API requests in a clean and efficient way.

Here are detailed examples of how Spatie integrates with Eloquent:

1. Filtering Queries Based on Request Parameters

Spatie's Query Builder allows you to filter Eloquent queries dynamically based on incoming HTTP request parameters. Instead of manually chaining `when` conditions, you can specify allowed filters declaratively.

Example:

php
use Spatie\QueryBuilder\QueryBuilder;

$users = QueryBuilder::for(User::class)
    ->allowedFilters('name')
    ->get();

This will filter users whose `name` contains the string provided in the request query parameter `filter[name]` (e.g., `/users?filter[name]=John`)[1][7].

2. Including Eloquent Relationships Dynamically

You can include related models (eager loading) dynamically via request parameters, which is useful for APIs that need to optionally load relations.

Example:

php
$users = QueryBuilder::for(User::class)
    ->allowedIncludes('posts')
    ->get();

This will load users along with their `posts` if the request includes `include=posts` (e.g., `/users?include=posts`)[1][7].

3. Sorting Results

Spatie Query Builder supports sorting results by specified columns, including multi-column sorting and custom sorting logic.

Example:

php
$users = QueryBuilder::for(User::class)
    ->allowedSorts('id', 'name')
    ->get();

A request like `/users?sort=-id,name` sorts users by descending `id` and then ascending `name`[1][7].

4. Combining with Existing Eloquent Queries

You can start with an existing Eloquent query builder instance and then apply Spatie's Query Builder on top, preserving scopes, soft deletes, and other query constraints.

Example:

php
$query = User::where('active', true);

$users = QueryBuilder::for($query)
    ->withTrashed() // includes soft deleted models
    ->allowedIncludes('posts', 'permissions')
    ->where('score', '>', 42)
    ->get();

This shows how Spatie integrates seamlessly with existing Eloquent queries and scopes[1][7].

5. Selecting Specific Fields

Spatie allows limiting the fields retrieved from the database, which is useful for optimizing API responses.

Example:

php
$users = QueryBuilder::for(User::class)
    ->allowedFields(['id', 'email'])
    ->get();

A request like `/users?fields[users]=id,email` will return only the `id` and `email` attributes for each user[1][7].

6. Custom Filters and Scopes

You can define custom query scopes on your Eloquent models and expose them as filters through Spatie Query Builder.

For example, in an `Apartment` model:

php
public function scopePriceFrom(Builder $query, $price): Builder
{
    return $query->where('price', '>=', $price);
}

Then use it in the query builder:

php
$apartments = QueryBuilder::for(Apartment::class)
    ->allowedFilters(['price_from'])
    ->get();

This allows filtering apartments with prices greater than or equal to a given value via `filter[price_from]` in the request[2].

7. Custom Sorting Classes

Spatie also supports creating custom sorting logic by defining sorting classes, allowing you to tailor sorting beyond simple column sorting.

Summary

Spatie's integration with Laravel Eloquent ORM enhances query building by:

- Extending Eloquent's query builder with filtering, sorting, and including relations based on HTTP requests.
- Allowing declarative and dynamic query constraints without verbose conditional logic.
- Supporting custom filters and sorting through Eloquent scopes and custom classes.
- Seamlessly working with existing Eloquent queries, scopes, and soft deletes.
- Enabling field selection to optimize data retrieval.

This makes Spatie Query Builder a powerful tool for building flexible and maintainable API endpoints with Laravel Eloquent[1][2][7].

Citations:
[1] https://spatie.be/docs/laravel-query-builder/v6/introduction
[2] https://redberry.international/spatie-query-builder-in-laravel/
[3] https://spatie.be/docs/laravel-permission/v6/basic-usage/new-app
[4] https://laracasts.com/discuss/channels/code-review/spatie-eloquent-sortable-please-help-to-integrate-spatie-code-help?page=0
[5] https://spatie.be/docs/laravel-model-states/v2/01-introduction
[6] https://spatie.be/docs/laravel-permission/v6/basic-usage/basic-usage
[7] https://github.com/spatie/laravel-query-builder
[8] https://stackoverflow.com/questions/78249743/laravel-spatie-permission-many-to-through-query