PHP Laravel Eloquent Data Type Conversion(Casting) Examples – laravel cast

Today, We want to share with you laravel cast.In this post we will show you PHP Laravel Eloquent Data Type Conversion(Casting) Examples, hear for getattribute laravel we will give you demo and example for implement.In this post, we will learn about Simple PHP Data Type Conversion with an example.

PHP Laravel Implicit and Explicit Type Casting

Laravel Eloquent provides a convenient way to change the data type of attributes using attribute casting.

There are the list of the “Attribute Casting” in Laravel.

array, boolean, collection, date, datetime, decimal:, double, encrypted, encrypted:array, encrypted:collection, encrypted:object, float, integer, object, real, string, timestamp or many more.

public function getTax($value)
    return (string) $value;

example like below.

$member = App\Member::find(1);

dd($member->tax) // string("100.85")

Array & JSON Casting

$member = App\Member::find(1);

$options = $member->options;

$options['key'] = 'value';

$member->options = $options;


add them to the $casts property of the model class with their desired type.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
    protected $casts = [
        'product_type'  =>  'boolean',
        'qty'       =>  'integer'

The $casts property should be an array where the key is the name of the attribute and value is the type of attribute being cast.

dd($product->product_type); // true

I hope you get an idea about PHP Laravel Eloquent Data Type Conversion(Casting) Examples.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment