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

Luka's avatar
Level 1

How can I use replace in Query?

I try to use Replace in my Query because I have categories in the Database, which might have a - inside them and my URL got - so to make sure I can compare, they both need to be the same. In MySQL it would look like this:

select * from `posts` inner join `categories` on `posts`.`category_id` = `categories`.`id`     where  REPLACE(category,' ','-') = 'Bits-Bobs and others' 

So I tried:

$posts = Post::where('posts.public',1)
                   ->join('categories', 'posts.category_id', '=', 'categories.id')
                   ->where(REPLACE(category,' ','-'),$cat)
                   ->orderBy('posts.id', 'desc')->paginate(5);

but I get a Call to undefined function App\Http\Controllers\REPLACE() How I can achieve to have a Replace on the column of the Database?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Use whereRaw() is you want a native function in the query:

->whereRaw("REPLACE(category,' ','-') = ?",[$cat])
1 like
Luka's avatar
Level 1

:-) Ahhh. Fantastic. Thank you so much !! The change you suggested works.

Please or to participate in this conversation.