dedmytro / laravel-model-related-fields
Provide an ability to add related fields/columns to all model Eloquent queries
Requires
- php: ^7.2.5|^8.0
- illuminate/support: ^7.0|^8.0
Requires (Dev)
- mockery/mockery: ^1.0
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.0
README
Provide an ability to add related fields/columns to all model Eloquent queries without additional database queries. It uses sub SELECT and joins so take into account extra database load when database has a lot of records.
Table of contents
Installation
To get the latest version of Laravel Model Related Fields
, simply require the project using Composer:
$ composer require dedmytro/laravel-model-related-fields
Or manually update require
block of composer.json
and run composer update
.
{ "require": { "dedmytro/laravel-model-related-fields": "^0.1" } }
Using
Add HasRelatedFields
trait to your model and define method addRelatedFields()
which returns array related fields you want to load on each Model query.
On example below you can see how to load related field through many relations and load SUM() of HasMany relation.
use Illuminate\Database\Eloquent\Model; use DeDmytro\LaravelModelRelatedFields\RelatedField; use DeDmytro\LaravelModelRelatedFields\Traits\HasRelatedFields; // ... class Order extends Model { use HasRelatedFields; // ... protected function addRelatedFields(): array { return [ 'country_currency' => 'event.company.country.currency', 'total' => new RelatedField('items.total', function ($query) { $query->selectRaw('SUM(price)'); }), ]; }
where
'event.company.country.currency'
is the same as $order->event->company->country->currency
'items.total'
is the same as $order->items()->sum('price')
As an alternative you can use $relatedFields
property for simple fields, without RelatedField
class usage. Property
and method result array will be be merged.
use Illuminate\Database\Eloquent\Model; use DeDmytro\LaravelModelRelatedFields\RelatedField; use DeDmytro\LaravelModelRelatedFields\Traits\HasRelatedFields; // ... class Order extends Model { use HasRelatedFields; // ... protected $relatedFields = [ 'country_currency' => 'event.company.country.currency', ]; protected function addRelatedFields(): array { return [ 'total' => new RelatedField('items.total', function ($query) { $query->selectRaw('SUM(price)'); }), ]; }
The result of query:
$order = Order::first();
you will get Order model with all fields plus additional related fields:
[ "id" => 1, // ... "country_currency" => "USD", "total" => 25.00, ]
How to disable/enable
Disable globally
To disable related fields for all models by default,
- publish config and change default value
'enabled' => false
- add env variable
ENABLE_MODEL_RELATED_FIELDS=false
Disable for particular model
Add protected $enableRelatedFields = false
protected $enableRelatedFields = false;
Disable for current query
$order = Order::withoutRelatedFields()->first();
Enable for current query if disabled globally
$order = Order::withRelatedFields()->first();