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

deepu07's avatar
Level 11

Select Statement column cast string to integer

Hi Mates, I'm in a scenario where I need to cast from string to integer in Select statement. I tried a couple of ways but it didn't work out for me. any help/suggestion that would be great. TIA

$students = Student::select([
            'id',
            'name',
	    'year',
            'subjects->subject5_number as subject5_number'
        ])
        ->where('year', 2019)
        ->orderBy('subject5_number')->get();
0 likes
6 replies
Snapey's avatar

all ok if you just retrieve it as it is?

You could create a cast in the eloquent model?

deepu07's avatar
Level 11

@snapey here subjects is the JSON type column in DB. I just wanna return subject5_number is an integer. I have added casts attribute to the model like this

protected $casts = ['subject5_number' => 'integer'];

but still, I'm getting value as string type.

Snapey's avatar

not sure how you can just cast it to an integer when its a json object?

1 like

Please or to participate in this conversation.