options` (no parens) must: * * - return an Eloquent Collection * - whose entries are FormFieldOption instances * - lazily lazy-load on first access (1 query for the parent fetch * plus 1 query for the lazy-load — no surprise extra reads) * * Tested for both polymorphic owners — FormField and FormFieldLibrary. */ final class FormFieldOptionsAccessTest extends TestCase { use RefreshDatabase; public function test_form_field_options_resolves_to_morph_many_collection_with_lazy_load(): void { $org = Organisation::factory()->create(); $schema = FormSchema::factory()->create(['organisation_id' => $org->id]); FormField::factory() ->withOptions(['XS', 'S', 'M']) ->create([ 'form_schema_id' => $schema->id, 'field_type' => FormFieldType::SELECT->value, 'slug' => 'shirtmaat', ]); DB::flushQueryLog(); DB::enableQueryLog(); // Fresh fetch — no with('options') eager-load. The lazy-load // happens on first $field->options access. $field = FormField::query()->where('slug', 'shirtmaat')->first(); $options = $field->options; DB::disableQueryLog(); $queries = DB::getQueryLog(); $this->assertInstanceOf(Collection::class, $options); $this->assertNotEmpty($options); $this->assertInstanceOf(FormFieldOption::class, $options->first()); $this->assertSame(['XS', 'S', 'M'], $options->pluck('value')->all()); // Exactly two queries: 1× FormField fetch + 1× lazy-load options. $this->assertCount( 2, $queries, sprintf( 'Expected exactly 2 queries (parent fetch + lazy-load options); got %d. Queries: %s', count($queries), json_encode(array_column($queries, 'query')), ), ); } public function test_form_field_library_options_resolves_to_morph_many_collection_with_lazy_load(): void { $org = Organisation::factory()->create(); FormFieldLibrary::factory() ->withOptions(['a', 'b']) ->create([ 'organisation_id' => $org->id, 'slug' => 'lib-select', ]); DB::flushQueryLog(); DB::enableQueryLog(); $library = FormFieldLibrary::query()->where('slug', 'lib-select')->first(); $options = $library->options; DB::disableQueryLog(); $queries = DB::getQueryLog(); $this->assertInstanceOf(Collection::class, $options); $this->assertNotEmpty($options); $this->assertInstanceOf(FormFieldOption::class, $options->first()); $this->assertSame(['a', 'b'], $options->pluck('value')->all()); $this->assertCount( 2, $queries, sprintf( 'Expected exactly 2 queries (parent fetch + lazy-load options); got %d. Queries: %s', count($queries), json_encode(array_column($queries, 'query')), ), ); } }