Laravel Case Insensitive Model Relationships

Normally, for case insensitive where queries, you can use the ‘ILIKE’ operator. But if you’re linking a prepopulated dataset, there’s a chance where a foreign key string doesn’t quite match another table’s key.

There’s not too much info on getting case insensitive relationships working other than digging into the database dictionary and building your own master class to pass a strtolower on the keys.

Thankfully @TishoTM created a package called Eloquent Ci Relations to address this concern not too long ago and was kind enough to update it to work with Laravel 6 & 7 (though the readme might says otherwise).


composer require tishotm/eloquent-ci-relations


use Illuminate\Database\Eloquent\Model;
use TishoTM\Eloquent\Concerns\HasCiRelationships;

class Item extends Model
    use HasCiRelationships;

    ... relations

I didn’t have much luck but thankfully Tisho responded.

Technically, the eloquent-ci-relations package is for eagerly loaded relations. Your example above describes lazy-loaded relations. In other words with or without the CI relations used, the result is the same, as expected. It is expected to load both sales records. Also, please, check your DB collation. It needs to be case-insensitive.

The proper way to test the CI relations is with.

>>> App\Brand::with('sales')->where('name', 'KIWI')->first();

Thank you, Tisho!

Leave a Comment