Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel concat in query (where condition)

Tags:

sql

php

laravel

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?

like image 201
Jonathan Avatar asked Sep 06 '25 11:09

Jonathan


2 Answers

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."%");
like image 141
user1669496 Avatar answered Sep 08 '25 22:09

user1669496


Use orWhereRaw to execute a raw where query:

$query->orWhereRaw("CONCAT(`nvp`, ' ', `vpv`) LIKE ?", ['%'.$this->searchNeedle.'%']);
like image 38
Joseph Silber Avatar answered Sep 08 '25 23:09

Joseph Silber