Model::$withCount for polymorphic models + Eloquent\Builder::where(\Closure) triggers unexpected bound parameter mismatching.
Related codes:
/**
* Add a basic where clause to the query.
*
* @param string|array|\Closure $column
* @param string $operator
* @param mixed $value
* @param string $boolean
* @return $this
*/
public function where($column, $operator = null, $value = null, $boolean = 'and')
{
if ($column instanceof Closure) {
$query = $this->model->newQueryWithoutScopes(); // <---
$column($query);
$this->query->addNestedWhereQuery($query->getQuery(), $boolean);
} else {
$this->query->where(...func_get_args());
}
return $this;
}
/**
* Get a new query builder that doesn't have any global scopes.
*
* @return \Illuminate\Database\Eloquent\Builder|static
*/
public function newQueryWithoutScopes()
{
$builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
// Once we have the query builders, we will set the model instances so the
// builder can easily access any information it may need from the model
// while it is constructing and executing various queries against it.
return $builder->setModel($this)
->with($this->with)
->withCount($this->withCount); // <---
}
I think Eloquent\Builder::where(\Closure) expects Model::newQueryWithoutScopes() to return Eloquent\Builder exactly without bindings, but actually it may contain bindings for polymorphic relation: *able_type = ?

The last two mismatching bound parameters "post", "post" trigger SQL error.
This is a known issue: #23957
@staudenmeir Should I always use Model::addGlobalScope() instead? However it has many different behaviors. For instance, Model::refresh() load attributes from Model::$withCount, not from Model::addGlobalScope().
I never plan to use Model::$withCount for production use, but I'm using it for a temporary implementation until implementing counter caches.
I don't know a good workaround for this problem. We are working on a solution: #24000
@staudenmeir I'll appreciate for your great try. Thank you
Most helpful comment
I don't know a good workaround for this problem. We are working on a solution: #24000