codingpaws / laravel-findby
Ruby-like findBy in your Laravel model queries.
Installs: 4 063
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Forks: 0
pkg:composer/codingpaws/laravel-findby
Requires
- illuminate/database: ^8.38 | ^9.0
- illuminate/support: ^8.38 | ^9.0
Requires (Dev)
- orchestra/testbench: ^6.17
- phpunit/phpunit: ^9.5
README
The codingpaws/laravel-findby library allows you to use the modern PHP 8.0 named arguments in Laravel’s eloquent queries similar to Ruby’s Active Record find_by.
class User extends Model
{
use CodingPaws\FindBy\FindBy;
}
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',
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 FindBy) 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 nativewherefindByNot, works like the nativewherebut inverted (using!=instead of=)orFindBy, works like the nativeorWhereorFindByNot, works like the nativeorWherebut inverted (using!=instead of=)
All methods support using arrays as value. For example,
Book::findBy(
genre: ['SciFi', 'Adventure', 'Drama'],
)->get();
queries all books where the genre column is either SciFi, Adventure, or Drama.
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. ❤️