user14101200
user14101200

Reputation:

How to Cast String into int in Laravel model

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?

Upvotes: 4

Views: 29122

Answers (4)

ash__939
ash__939

Reputation: 1599

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.

Upvotes: 3

STA
STA

Reputation: 34668

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.

Upvotes: 0

Bahaeddine
Bahaeddine

Reputation: 119

try this:

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

Upvotes: 0

Naveed Ali
Naveed Ali

Reputation: 1045

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',
];

Upvotes: 12

Related Questions