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

Rate this post

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.

Read Also:  failed to load resource: the server responded with a status of 404 (not found)

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

example like below.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    /**
     * The attributes that should be casting to native types.
     *
     * @var array
     */
    protected $casts = [
        'tax' => 'string',
    ];
}

Free Live Chat for Any Issue

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

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

Array & JSON Casting

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'options' => 'array',
    ];
}

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

$options = $member->options;

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

$member->options = $options;

$member->save();

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

Read Also:  Laravel 5/6/7 Carbon date format Example

Example

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

Download

I hope you get an idea about PHP Laravel Eloquent Data Type Conversion(Casting) Examples.
I would like to have feedback on my infinityknow.com 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.