Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vertoo's avatar

Eloquent query for morphToMany - problem with generated SQL code

I have problem with Eloquent morphToMany

public function categories()
{
    return $this->morphToMany(Category::class, 'categoryable')->withTimestamps();
}

# part of query
return $this->builder->whereHas('categories', function ($query) use ($val) {
    $query->whereIn('categories.id', $val);
});

this part of query produce MySQL code (deleted not required here parts of code):

select
    *
from
    `categories`
INNER join `categoryables` on `categories`.`id` = `categoryables`.`category_id`
where
      `categoryables`.`categoryable_type` = 'App\Models\Volunteering'

Tested in DBeaver and this code returns empty results, when I look to database table then should be any results. Comment out WHERE clause and records are showed. So, I copy and paste "App\Models\Volunteering" to query, no, it's correct. Try use LIKE with % and without, no records. But when I test with

WHERE `categoryables`.`categoryable_type` LIKE 'App%'

query shows results. But this query is generated by Eloquent. What is wrong?

Tested on MySQL 5.7 and MariaDB 10.2, same problem.

0 likes
1 reply
vertoo's avatar

Problem resolved. My mistake, query was complex, here is just small part and it's OK. Just Telescope display it without double backslashes.

Please or to participate in this conversation.