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.

Read Also:  PHP Domdocument Get selectors Class Tags Table img Elements

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

$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 6 Eloquent WHERE Like query 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

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.