4

This is my solution. I wrote this inside my Model class. (ratings is a string type)

$code = (int)$ratings;

But I need to change $ratings when retrieving it from the database. how can I do it?

4 Answers 4

12

we have a property of a model called cast in which you can specify your column names just like below:

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'ratings' => 'integer',
];
Sign up to request clarification or add additional context in comments.

Comments

3

From Laravel Documentation:

Attribute Casting The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, and timestamp. When casting to decimal, you must define the number of digits (decimal:2).

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'ratings' => 'integer',
    ];
}

Attributes that are null will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship.

Comments

0

try this:

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

Comments

0

You cast attributes in Eloquent by adding a protected $casts int to your model :

protected $casts = [
    'ratings' => 'integer',
];

This casts your field to an integer using return (int) $value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.