Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to lowercase nested relation field in Laravel Eloquent query?

I have a search mechanism like this, with "client.partner" nested relation:

$query->whereHas("client.partner", function ($query) use ($searchterm, $relation) {
    $query->when($relation === "contains", function ($query) use ($searchterm, $relation) {
        $query->where("partners.name", "LIKE", "%" . strtolower($searchterm) . "%");
    });   
});

The question is, that how "partners.name" in where clause can be lowercased.

I tried to use LOWER() function, as follows, but it did not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
 $query->where(LOWER("partners.name"), "LIKE", "%" . strtolower($searchterm) . "%");
...

Any idea?

>Solution :

You can use the DB::raw() method to lowercase the value of the "partners.name" column in the where clause. Here is an example:

$query->whereHas("client.partner", function ($query) use ($searchterm, $relation) {
    $query->when($relation === "contains", function ($query) use ($searchterm, $relation) {
        $query->where(DB::raw("LOWER(partners.name)"), "LIKE", "%" . strtolower($searchterm) . "%");
    });   
});

The DB::raw() method allows you to write raw SQL expressions within the Eloquent query. In this case, we use the LOWER() SQL function to convert the value of "partners.name" to lowercase before comparing it with the search term.

Note: Make sure you import the DB facade at the top of your file:

use Illuminate\Support\Facades\DB;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading