themsaid/ergodnc

ErrorException: Undefined array key "tags"

chisumo2016 opened this issue · 1 comments

Tests\Feature\OfficeControllerTest::itIncludesImagesTagsAndUser
ErrorException: Undefined array key "tags"

/Users/os/Documents/projects/office-reservation/tests/Feature/OfficeControllerTest.php:121

/**
* @test
*/
public function itIncludesImagesTagsAndUser()
{
$user = User::factory()->create();
$tag = Tag::factory()->create();
$office = Office::factory()->for($user)->create();

    $office->tags()->attach($tag);
    $office->images()->create(['path' => 'image.jpg']);

    $response = $this->get('/api/offices');

    //$response->dump();

    $response->assertOk();
    //dd($response->json('data')[0]);
    $this->assertIsArray($response->json('data')[0]['tags']);
    $this->assertCount(1, $response->json('data')[0]['tags']);
    $this->assertIsArray($response->json('data')[0]['images']);
    $this->assertCount(1,$response->json('data')[0]['images']);
    $this->assertEquals($user->id, $response->json('data')[0]['user']['id']);

    //$response->dump();
}

Controller

public function index() : JsonResource
{
$offices = Office::query()//->orderBy('id','DESC')
->where('approval_status', Office::APPROVAL_APPROVED)
->where('hidden', false)
->when(request('host_id'),
fn($builder) => $builder->whereUserId(request('host_id')))
->when(request('user_id'), //user_id'
fn($builder) => $builder->whereRelation('reservations', 'user_id' , '=' , request('user_id')))
->when(
request('lat') && request('lng'),
fn($builder) => $builder->nearestTo(request('lat'),request('lng')), //Otherwise
fn($builder) => $builder->orderBy('id', 'ASC')//oldest record
)
//latest('id')
->with(['images', 'tags', 'user'])//Problem
->withCount(['reservations' => fn($builder) => $builder->where('status', Reservation::STATUS_ACTIVE)])
->paginate(20);

    return OfficeResource::collection(
        $offices
    );
}

Hi,
Have you defined the tags relationshio in Office Model file

public function tags()
{
return $this->belongsToMany(Tag::class,'offices_tags');
}

Please check all the relationships again