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

Dunsti's avatar

Eloquent conditional query based on database-field

Hi,

I have a table like this:

+----+------------------+-----------+
| id | mail_domain      | type      |
+----+------------------+-----------+
|  1 | my_app.test      | EQ        |
|  2 | another_app.test | ENDS_WITH |
+----+------------------+-----------+

I want to query this table depending on field type like this

if 'type' == 'EQ'
Model::where('mail_domain' , $search)

if 'type' == 'ENDS_WITH'
Model::where('mail_domain', 'like', '%' . $search)

I know, I can use when() but the documentation only tells about some condition based on a variable:

$role = $request->input('role');

$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();

How can I relate the when() to a database-field instead of an separate variable?

0 likes
7 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Something like this

Model::query()
->where(function($query) use ($search) {
    $query->where('mail_domain', 'like', '%' . $search)->where('type', 'ENDS_WITH');
})
->orWhere(function($query) use ($search) {
    $query->where('mail_domain', $search)->where('type', 'EQ');
})->get();
1 like
Dunsti's avatar

Thanks, that pushed me in the right direction.

But I have another problem I just discovered, when testing this solution:

$search = 'foo-anotherapp.test'
'mail_domain' = 'anotherapp.test'


->where('mail_domain', 'like', '%' . $search)

this doesn't give the right result - the % would be needed on "the other side"

Is there an "Eloquent" solution for this?

Sinnbeck's avatar

@Dunsti You mean, you search for foo-anotherapp.test and get a hit on anotherapp.test? No that would require you to split the input string up yourself, or use fulltext search (laravel scout)

Dunsti's avatar

@Sinnbeck yes, that's what I mean :D (damn buggy legacy project)

Thanks anyways for you help ! much appreciated !

Sinnbeck's avatar

@Dunsti If you can show how its done in the legacy project, perhaps we can help you update the code to eloquent :)

And happy to help

Please or to participate in this conversation.