a1dbox/laravel-model-accessor-builder

You can build query on model accessor. Sort or filter by accessor, and at the same time it's a regular model accessor

v1.0.3 2022-08-17 21:24 UTC

This package is auto-updated.

Last update: 2024-11-18 02:31:07 UTC


README

Latest Version on Packagist Total Downloads

You can build query on model accessor. Sort or filter by accessor, and at the same time it's a regular working accessor

Installation

You can install the package via composer:

composer require a1dbox/laravel-model-accessor-builder

Usage

Use the HasAccessorBuilder trait in your model to provide work of accessor builder:

use A1DBox\Laravel\ModelAccessorBuilder\Concerns\HasAccessorBuilder;

class User extends Model
{
    use HasAccessorBuilder;
}

Create Accessor for attribute

Laravel 8.x accessor defining style
class User extends Model
{
    use HasAccessorBuilder;
    
    public function getFullNameAttribute()
    {
        return AccessorBuilder::make(
            fn (AccessorBuilder\BlueprintCabinet $cabinet) => $cabinet->trim(
                $cabinet->concat(
                    $cabinet->col('name'),
                    $cabinet->str(' '),
                    $cabinet->col('last_name'),
                )
            ),
        );
    }
}

As example, code above will do same as this one, when resolving accessor value:

return trim($this->name . ' ' . $this->last_name);

Example #1

Here, the full_name attribute contained in model $attributes after query And when using accessor ->full_name, the value will be taken from $attributes

$user = User::query()
    ->withAccessor('full_name')
    ->find(1);

echo $user->full_name; //John Doe

SQL Query executed:

SELECT
    *,
    trim(concat(name, ' ', last_name)) AS full_name
FROM users WHERE id = 1

Example #2

Here, the full_name attribute NOT contained in $attributes variable of model, and when using accessor $user->full_name, the value will be built from model $attributes

$user = User::find(1);

echo $user->full_name; //John Doe

SQL Query executed:

SELECT * FROM users WHERE id = 1

Example #3

Get all users ordered by full_name

$users = User::query()
    ->withAccessor('full_name')
    ->orderBy('full_name')
    ->get();

Example #4

Filter users by full_name

$users = User::query()
    ->withAccessor('full_name')
    ->where('full_name', 'John Doe')
    ->get();

You can pass array to withAccessor method

$users = User::query()
    ->withAccessor(['full_name', 'full_address'])
    ->get();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.