php - Scope and Relation doesn't work together - Laravel
Solution:
I fixed it by adding a custom scope to Contacts model
public function scopeActiveFollowings($query)
{
return $query->join('users', function($join)
{
$join->on('users.ID', '=', 'contacts.contact_id')
->where('activated', '=', 1);
});
}
Answer
Solution:
Laravel model has a property called query.
This property is used automatically when you call a query for the model these two statements are exactly the same:
User::query()->where('id',1)->get();
User::where('id',1)->get();
When you call query() directly or indirectly, Laravel register the scopes in this line
when you use $this->hasMany('App\Models\Contacts','user_id','ID')
the result will be from class HasMany and this class doesn't have a method called active(), this is why you see this error.
to fix it, you have to apply the scope when you use User model query:
$result=User::query()->activated()->with('followings')->findOrFail(1);
if you want the followings count for the activated user using scope, you should apply this scope on Following Model:
public function scopeHasActivedUser($query)
{
return $query->whereHas('user', function($query)
{
$query->where('users.activated', 1);
});
}
In the controller:
$fllowingsCountForActivatedUser=Fllowing::query()->hasActivedUser()->count();
If I were you, I would get the result this way:
$user=User::withCount(['followings'=>function($query){
$query->where('users.activated', 1)})])->find(1);
now the $user model instance should have a property called 'followings_count' for the only activated followings count
Source