From 5f7f63f2edf84dcae14b98afb58a5e3d10775088 Mon Sep 17 00:00:00 2001 From: pxpm Date: Fri, 3 Jan 2025 12:20:40 +0000 Subject: [PATCH] add append attributes docs --- 6.x/crud-operation-fetch.md | 26 ++++++++++++++++++++++++++ 7.x-dev/crud-operation-fetch.md | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/6.x/crud-operation-fetch.md b/6.x/crud-operation-fetch.md index 2685f7b3..cc13a988 100644 --- a/6.x/crud-operation-fetch.md +++ b/6.x/crud-operation-fetch.md @@ -84,6 +84,32 @@ public function fetchUser() { } ``` +**Adding attributes to fetched models without appends** + +It's already possible to add attributes to the fetched models using the `appends` property in the model. However, this method has some drawbacks, like the fact that the appended attributes will be added to all instances of the model, whenever they are used, not only when they are fetched. If you want to add attributes to the fetched models without using the `appends` property in the model, you can use the `append_attributes` in the fetch configuration. For example: + +```php +public function fetchUser() { + return $this->fetch([ + 'model' => User::class, + 'append_attributes' => ['something'], + ]); + } + +// User.php model +public function something(): Attribute +{ + return Attribute::make( + get: function (mixed $value, array $attributes) { + return $attributes['something_else']; + }, + ); +} + +// and in your field definition +CRUD::field('my_ajax_field')->attribute('something'); +``` + ## Using FetchOperation with `select2_ajax` filter diff --git a/7.x-dev/crud-operation-fetch.md b/7.x-dev/crud-operation-fetch.md index 2685f7b3..cc13a988 100644 --- a/7.x-dev/crud-operation-fetch.md +++ b/7.x-dev/crud-operation-fetch.md @@ -84,6 +84,32 @@ public function fetchUser() { } ``` +**Adding attributes to fetched models without appends** + +It's already possible to add attributes to the fetched models using the `appends` property in the model. However, this method has some drawbacks, like the fact that the appended attributes will be added to all instances of the model, whenever they are used, not only when they are fetched. If you want to add attributes to the fetched models without using the `appends` property in the model, you can use the `append_attributes` in the fetch configuration. For example: + +```php +public function fetchUser() { + return $this->fetch([ + 'model' => User::class, + 'append_attributes' => ['something'], + ]); + } + +// User.php model +public function something(): Attribute +{ + return Attribute::make( + get: function (mixed $value, array $attributes) { + return $attributes['something_else']; + }, + ); +} + +// and in your field definition +CRUD::field('my_ajax_field')->attribute('something'); +``` + ## Using FetchOperation with `select2_ajax` filter