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

realtebo's avatar

How to create a raw query for substring but portable?

I need to create a substring(field, 0, -10) to keep only last 10 chars of a string.

I am using a raw query here because i need to do a lower(field) LIKE

this because i am using both mysql and postgres (some customers have mysql and others postgres).

I remember there was a system to use "getSubstringExpression()" of laravel, that is automatically passed to specific grammar of current connection

i tried

... ->query()->getSubstringExpression()

DB::raw()->getSubstringExpression()...

I have no idea of how to use getExpression s

0 likes
4 replies
Sinnbeck's avatar

This is the method syntax getSubstringExpression($string, $start, $length = null)

It is part of doctrine, not laravel (through eloquent is built on top of doctrine)

1 like
realtebo's avatar

I ended using right, it's the same on both platform.

->whereRaw("RIGHT(num_prot_esterno, 10) LIKE '%/" . $anno . "'")

Sinnbeck's avatar

@realtebo you should move the variable to the second param, to avoid sql injection

->whereRaw("RIGHT(num_prot_esterno, 10) LIKE '%?", [$anno])

Please or to participate in this conversation.