Laravel 7 (with Fractal) not including relationship counts when using withCount method

202 Views Asked by At

I'm a relatively new PHP developer, so I might get some of this wrong.

PHP: 7.4 Laravel/Lumen: 7.0 Fractal: 0.13-dev (I think)

I have a model, Programs.

<?php

use Illuminate\Database\Eloquent\Model;

class Program extends Model
{
    public $guarded = ['id'];

    public function sites()
    {
        return $this->belongsToMany(Site::class, 'programs_sites');
    }
}

?>

which has a belongsToMany relationship with Sites.

?>

<?php

use Illuminate\Database\Eloquent\Model;

class Site extends Model
{
    public $guarded = ['id'];
}

?>

I'm able to use this ProgramController method:

public function index(Request $request) {
    $query = Program::withCount('sites')->whereClientId($request->get('client_id'));

    $products = $query->get();

    return $this->fractal->respondWithCollection($products, new ProgramTransformer);
}

to return the nested relationship from the API with the following URL: http://local:8081/ads/api/programs?client_id=130785&includes%5B0%5D=sites

{
    "data": [
        {
            "id": 817,
            "name": "Daugherty Ltd",
            "sites": [
                {
                    "id": 13,
                    "name": "MyDomain.com",
                },
            ],
        }
    ],
    "meta": {
        "count": 1
    }
}

When I remove the includes query param, the sites block drops off as expected. However my front end also needs counts of the nested relationships. I understand that I could simply run a count of the sites array, but I'd like to get it from the service if possible.

The Laravel docs indicate that there's a withCount which "will place a {relation}_count column on your resulting models". However, in my case it's not working. When hitting this via Postman I'd expect to see an additional property on the Program model, "site_count": 1. But I'm not seeing any additional properties, and no errors either.

Given my inexperience with PHP / Laravel my first assumption is that I'm doing something wrong, but I don't know what it might be. Can anyone offer insight into what I'm missing?

0

There are 0 best solutions below