Jonathan
Jonathan

Reputation: 2021

Laravel concat in query (where condition)

I am new to laravel and face a problem building a simple query:

$query->orWhere("CONCAT(`nvp`, ' ', `vpv`)", 'LIKE', "%$this->searchNeedle%");

This line above is one of several conditions in an encapsulated query condition. I think the other lines are not necessary for this case but tell me if you need to see them.

I found out that the developer decided to add a

`

before and after the first orWhere/where param which cause the problem that I cant use a simple concat, because the line above will result in:

`CONCAT(`vpv`, ' ', `nvp`)` LIKE ?)' 
↑                         ↑
this                    & this

Since this is automagically added i cant remove it without overwriting a laravel-core function which i wont. Is there any SQL-based "hack" that handles these two ` ? Something in the way like 1 = 1, you know?

Maybe you have another solution for me to get the intended result, comparing one string with two rows in combination?

Upvotes: 28

Views: 53354

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219920

Use orWhereRaw to execute a raw where query:

$query->orWhereRaw("CONCAT(`nvp`, ' ', `vpv`) LIKE ?", ['%'.$this->searchNeedle.'%']);

Upvotes: 20

user1669496
user1669496

Reputation: 33048

Laravel does some stuff behind the scenes like adding in the tick marks for you.

Fortunately, it also offers a couple of tools to still get the job done for you...

For this type of thing, DB::raw() usually works really well. Try something like this...

$query->orWhere(DB::raw("CONCAT(`nvp`, ' ', `vpv`)"), 'LIKE', "%".$this->searchNeedle."%");

Upvotes: 62

Related Questions