kevslashnull / futuristic-eloquent-builder
Use PHP8 named arguments in your Laravel Eloquent queries
Requires
- illuminate/database: ^8.38
- illuminate/support: ^8.38
Requires (Dev)
- orchestra/testbench: ^6.17
- phpunit/phpunit: ^9.5
README
The Futuristic Eloquent Builder allows you to use the modern PHP 8.0 named arguments in Laravel’s eloquent queries similar to Ruby’s Active Record findBy
.
class User extends Model
{
use KevSlashNull\FuturisticEloquentBuilder\NamedParameterQuery;
}
User::findBy(
first_name: 'Jane',
role_id: 5,
is_admin: false,
)->get();
It also introduces a findByNot
method that is a shorthand for not equals (!=
):
Book::findByNot(
genre: 'SciFi',
genre: 'Adventure', // allowed!
legth: 'long',
)->findBy(genre: 'Drama', author: 'Dürrenmatt')->get();
This project is still in its early days. The technical solution builds on top of Laravel’s existing query builder. While adding new functionality we need to ensure that existing features keep working.
Installation
composer require kevslashnull/futuristic-eloquent-builder
The futuristic eloquent builder is opt-in per model. To perform queries with named arguments for a given model, use the trait (use NamedParameterQuery
) in its class.
Supported Methods
You can use these methods on your model (e.g. Book::findBy
) and on builders of that model (e.g. Book::where('id', 3)->findBy
).
findBy
, works like the nativewhere
findByNot
, works like the nativewhere
but inverted (using!=
instead of=
)orFindBy
, works like the nativeorWhere
orFindByNot
, works like the nativeorWhere
but inverted (using!=
instead of=
)
Technical background
Most of the magic happens in the NamedBuilder
class. It extends eloquent’s Builder
class with the findBy
and findByNot
methods. Chaining where
and findBy
is possible by overriding the where
method and always returning a NamedBuilder
instance.
Version 1.0
of the library allowed named parameters in the where
query but it turned out to be impossible because.
In reality,
User::findBy(first_name: 'John', last_name: 'Doe', gender: 'male');
translates to
User::where('first_name', 'John')->where('last_name', 'Doe'->where('gender', 'male');
Everyone can contribute
The project is licensed under MIT. Everyone can contribute. ❤️