What Is Array And JSON Casting In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

The array cast type is particularly useful when working with columns that are stored as serialized JSON.

What Is Array And JSON Casting In Laravel With Example

Array & JSON Casting

For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

Open User.php model file and implement code as below 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

So, for example
Create Route in Web.php file as below

Route::get('/cast ', 'demoController@cast')->name('cast');


Create demoController 

php artisan make:controller demoController -mcr


Open demoController.php in app\Http\Controller folder and implement code as below

public function cast()
{
    $user = User::find(1);

    $options = $user->options;

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

    $user->options = $options;

    $user->save();
}

Related Post