moses toh
moses toh

Reputation: 13162

How can I make laravel casting array on the model?

I try like this

Data type of votes_detail in database is json

My model like this :

<?php
class Store extends Model{  
    protected $fillable = [ ...,'votes_detail',...];
    protected $casts = [
        'votes_detail' => 'array',
    ];
}

My controller like this :

$store = Store::find($id)
$votes_detail = $store->votes_detail;
dd($votes_detail);

The result of dd($votes_detail) is :

{"1": "1", "5": "2"}

Why the result is still json?

The result should be an array

Whereas I've set the array in cast model

How can I solve this problem?

Upvotes: 1

Views: 16597

Answers (3)

Desh901
Desh901

Reputation: 2723

You could use Laravel accessors. In you model define a method called exactly getVotesDetailAttribute($details):

public function getVotesDetailAttribute($details)
{
    return json_decode($details, true);
}

then when you will call $store->votes_detail you will get the expected result.

After that you can use mutators to convert an array back to JSON when it is saved back in the DB. Define the method setVotesDetailAttribute($value) as follows:

public function setVotesDetailsAttribute($value)
{
     $this->attributes['votes_detail'] = json_encode($value);
}

Upvotes: 4

Sagar Gautam
Sagar Gautam

Reputation: 9369

I think you are storing array data after json_encode() to a column which is not defined as json() in the migration like:

$table->text('votes_detail');

or

$table->integer('votes_detail');

And seems you have defined votes_detail as string, number or something else.

This is the reason behind your problem. So, define column type as json in migration like:

$table->json('votes_detail');

And then refresh your migration, your casting in the model will work and you will get your desired array.

Upvotes: 0

Md. Abutaleb
Md. Abutaleb

Reputation: 1635

You can easily do it by converting your data to the array by using toArray() function. So it should be like

$store = Store::find($id)->toArray();

//$store contain a array.

$votes_detail = $store['votes_detail'];

make it dd($votes_detail) and get your desire result.

Upvotes: 0

Related Questions