kevslashnull/futuristic-eloquent-builder

This package is abandoned and no longer maintained. The author suggests using the codingpaws/laravel-findby package instead.

Use PHP8 named arguments in your Laravel Eloquent queries

1.3 2021-04-26 13:16 UTC

This package is auto-updated.

Last update: 2021-06-14 23:18:54 UTC


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 native where
  • findByNot, works like the native where but inverted (using != instead of =)
  • orFindBy, works like the native orWhere
  • orFindByNot, works like the native orWhere 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. ❤️