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

eddy1992's avatar

Laravel db::raw query for the query scope.

Hi I have a query scope in laravel and I have a column named km which is varchar. Now I want to write a raw query scope for it. The problem is it wont search for the varchar. So need to cast km to unsigned.

Product::km($kmFrom, $kmTo);
    public function scopeKm($query, $kmFrom, $kmTo)
    {   
        $kmFrom = (int)$kmFrom;
        $kmFrom = (int)$kmTo;

        if((count($kmFrom) > 0) && count($kmTo) > 0){ 

            return $query->whereBetween('km', [$kmFrom, $kmTo]);   
        }
        return $query;
    }

I want to write the db raw query for the above in which I cast the km column to unsigned in the raw query.

0 likes
3 replies
36864's avatar

I'm having a hard time understanding your code.

What are you expecting $kmFrom and $kmTo to be going into that function, why are you casting them to int, and what are you hoping to achieve with the count() verifications?

And in any case, why are you storing km as a varchar in the first place instead of unsigned to avoid having to cast it?

eddy1992's avatar

@36864 thank you for you response please check I have edited my question

36864's avatar
36864
Best Answer
Level 13

I don't see any edits that answer any of the questions I've asked, but never mind. I saw your previous question's code and it's pretty clear from this post that you've just been trying everything you can think of, and nothing has worked because you've been trying to fix this in the wrong place.

The correct way to fix your problem would be to change the km column in your database to int instead of varchar.

If you can't do that,

whereRaw('cast(km as UNSIGNED) between ? and ?', [$kmFrom, $kmTo]);
1 like

Please or to participate in this conversation.