I have Clients, which have Users, which have Surveys with a many-to-many table. So user_surveys.
I'm wondering how I can count some relations deep. I would like to the count of all surveys the users have for that client
What I've tried
Client.php
public function countSurveys()
{
$employees = $this->employees;
// this returns Property [surveys] does not exist on this collection instance.
return $employees->surveys->count();
// Method whereHas does not exist
return $employees->whereHas('surveys')->count();
}
This my employees method, which is a subset of Users
public function employees()
{
return $this->users()->whereHas('roles', function ($q) {
$q->where('name', 'employee');
});
}
And this is the User model
namespace App\Models;
use App\LoginToken; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
public function surveys()
{
return $this->belongsToMany(Survey::class, 'user_surveys', 'user_id', 'survey_id')
->withPivot('completed_on', 'status')
->withTimestamps();
}
public function journey()
{
return $this->belongsTo(Scan::class);
}
public function client()
{
return $this->belongsTo(Client::class);
}
}
It might be late, I might be confused and/or stupid. Looking forward to your responses!
dd($employees)
and tell us what object is that? – Marco Aurélio Deleuemployees()
function andEmployee
Model – Paras