John Davidson

php - Eloquent. Cast select's as integer within relationship?

0 comments
Message:


i'm trying to create a re-useable method which can get the minimum and maximum values from a table, but for any column I ask for.


So for example below I want to min and max of price. However this value is being returned as a string:


$result = [
"price" => [
"min" => "2200.00",
"max" => "45340.00"
]
];

I want to return this, and avoid additional manipulation of the data:


$result = [
"price" => [
"min" => 2200,
"max" => 45340
]
];

This is my current method.


public function vehiclesMinMax($column)
{
return $this->hasOne(Vehicle::class)
->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
->where($column, '>', 0)
->first();
}

What I tried to do is use withCasts, however this doesn't appear to be available for database/Query/Builder.php


public function vehiclesMinMax($column)
{
return $this->hasOne(Vehicle::class)
->selectRaw(new Expression("MIN({$column}) AS min, MAX({$column}) AS max"))
->withCasts([
'min' => 'integer',
])
->where($column, '>', 0)
->first();
}


My Answer:
In Laravel's Eloquent, you can cast the selected columns to specific data types using the `casts` property in your model.

For example, if you have a `User` model and you want to cast the `age` column to an integer, you can do the following:

php
namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
protected $casts = [
'age' => 'integer',
];
}


Now, when you retrieve a `User` instance, the `age` attribute will be automatically cast to an integer.

You can also cast other data types such as boolean, array, date, and JSON. Just specify the column name and the desired data type in the `casts` property of your model.

Rate this post

5 of 5 based on 8652 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us