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

jandk4014's avatar

Eloquent polymorphic return zero but query works in MySql

A difficult question to ask and even harder to find answers for. When I dump the query out to the screen and run in directly in MySql I get the desired results. However executing the code in the project produces zero models.

Migrations

Schema::create('part_base_parts', function (Blueprint $table) {
    $table->increments('id')->index('part_base_parts_id');
    $table->string('code')->nullable();
    $table->boolean('is_web')->default(0);
});
        
Schema::create('part_numbers', function (Blueprint $table) {
    $table->increments('id')->onDelete('cascade')->index('part_numbers_id');
    $table->string('code');
    $table->text('description')->nullable();
    $table->integer('status_id')->unsigned()->default(0);
    $table->foreign('status_id')->references('id')->on('statuses');
    $table->boolean('is_web')->default(0);
});

Models

class PartBasePart extends \App\Models\Base\PartBasePart
{
    protected $fillable = [
        'code',
        'part_type_id',
        'is_web',
        'unit_of_measurement_id'
    ];
    
    public function property()
    {
        return $this->morphMany(PartNumberProperty::class, 'propertable');
    }
}
class PartNumberProperty extends \App\Models\Base\PartNumberProperty
{
    protected $fillable = [
        'part_number_id',
        'propertable_id',
        'propertable_type'
    ];

    public function PartNumberProperty()
    {
        return $this->morphTo();
    }
}

The code that I'm attempting to execute is very simplistic.

Route::get('/test', function() {
    $pbp = App\Models\PartBasePart::find(9);
    echo $pbp->property;
});

The query produced from the above get request is:

select * from `part_number_properties` where `part_number_properties`.`propertable_id` = '9' and `part_number_properties`.`propertable_id` is not null and `part_number_properties`.`propertable_type` = 'App\Models\PartBasePart'

This request produces zero models when I execute from the site. However, if I take the query produced by Eloquent and put it into MySql, it works just fine. Any thoughts as to why? Could it be that I have my models in a sub-folder and I have and issue with "\" in propertable_type? If that was the case then why would the same query work in MySql?

0 likes
1 reply
jandk4014's avatar

For what it's worth I found out my solution. During a database seed I performed a massive import from LOAD DATA INFILE. Apparently, this MySQL command stripped out my slashes from the table. Rendering incorrect results. Why was the query returning back appropriate data, even though there was no slash in the field? I don't know.

Will correct the seed and move on.

Please or to participate in this conversation.