Skip to content

A free open source IT asset/license management system

Allow querying on cusotm fields fieldname directly by column name

snipeef64210ed260
diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.php
index d88083f031..3702d28fbb 100644
--- a/app/Http/Controllers/Api/AssetsController.php
+++ b/app/Http/Controllers/Api/AssetsController.php
@@ -371,6 +371,12 @@ class AssetsController extends Controller
$assets->where('assets.order_number', '=', strval($request->input('order_number')));
}
+ foreach ($all_custom_fields as $field) {
+ if ($request->filled($field->db_column_name())) {
+ $assets->where($field->db_column_name(), '=', $request->input($field->db_column_name()));
+ }
+ }
+
// This is kinda gross, but we need to do this because the Bootstrap Tables
// API passes custom field ordering as custom_fields.fieldname, and we have to strip
// that out to let the default sorter below order them correctly on the assets table.
diff --git a/tests/Feature/Assets/Api/AssetIndexTest.php b/tests/Feature/Assets/Api/AssetIndexTest.php
index c780a4aef1..96731260a5 100644
--- a/tests/Feature/Assets/Api/AssetIndexTest.php
+++ b/tests/Feature/Assets/Api/AssetIndexTest.php
@@ -4,6 +4,7 @@ namespace Tests\Feature\Assets\Api;
use App\Models\Asset;
use App\Models\Company;
+use App\Models\CustomField;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Testing\Fluent\AssertableJson;
@@ -168,6 +169,29 @@ class AssetIndexTest extends TestCase
->assertResponseContainsInRows($assetB, 'asset_tag');
}
+ public function test_assets_can_be_filtered_by_custom_field()
+ {
+ $this->markIncompleteIfMySQL('Custom Fields tests do not work on MySQL');
+
+ $field = CustomField::factory()->create();
+
+ $matchingAssets = Asset::factory()->count(3)->hasMultipleCustomFields([$field])->create();
+ foreach ($matchingAssets as $asset) {
+ $asset->{$field->db_column_name()} = 'target-value';
+ $asset->save();
+ }
+
+ // These assets have a null value for the custom field column and should not be returned
+ Asset::factory()->count(2)->create();
+
+ $this->actingAsForApi(User::factory()->superuser()->create())
+ ->getJson(route('api.assets.index', [
+ $field->db_column_name() => 'target-value',
+ ]))
+ ->assertOk()
+ ->assertJson(fn (AssertableJson $json) => $json->has('rows', 3)->etc());
+ }
+
public function test_gracefully_handles_malformed_filter()
{
$this->actingAsForApi(User::factory()->viewAssets()->create())