vendredi 17 mai 2019

Laravel cast array still returns a string

When retrieving a column I'd like to get it as an array, however it's returned as a string.

Migration

$table->text('balance')->nullable();

On the model (as per the Laravel docs)

protected $casts = [
   'balance' => 'array',
];

When saving data to the balance column

$exchange = Exchange::findOrFail($id);
$exchange->balance = json_encode($balance);
$exchange->save();

When retrieving the model

$exchanges = Exchange::orderBy('title')->get();

In the view

foreach($exchanges as $ex)
   echo gettype($ex->balance) // This returns string, not an array
endforeach

I'm puzzled as to why it's still a string while it should be an array. I've also tried the json instead of text column type in the migration, same result.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire