codingpaws/laravel-findby

Ruby-like findBy in your Laravel model queries.

2.3 2022-07-30 15:54 UTC

This package is auto-updated.

Last update: 2024-04-29 04:47:19 UTC


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 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 =)

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. ❤️