29

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?

1

2 Answers 2

64

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."%");
Sign up to request clarification or add additional context in comments.

4 Comments

Now the App wont crash but result in this: CONCAT(nvp, ' ', vpv) LIKE '%users name%' is null
I think my syntax was a little off, I just modified the answer.
I smell sql injection with this answer,` $this->searchNeedle` is coming directly from the user.
Laravel will handle the parameter binding for you so no chance of SQL injection. If the entire thing was wrapped in DB::raw() you'd be correct.
20

Use orWhereRaw to execute a raw where query:

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

3 Comments

It doen't work for me (SQL error). I fixed it by putting the % into the second argument: $query->orWhereRaw("CONCAT(nvp, ' ', vpv) LIKE ?", ["%".$this->searchNeedle."%"]);
may I ask you to have a look at a Laravel table join related question here : stackoverflow.com/questions/52149031/… ?
You must use ` instead of ' for the columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.