5

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.

2 Answers 2

6

If you config your model to cast an attribute to array, you don't need to convert it back to json when trying to store it, Laravel will handle this for you. From the docs:

Array & JSON Casting

...

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:

$user = App\User::find(1);

$options = $user->options;

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

$user->options = $options;

$user->save();

So in your case:

$exchange = Exchange::findOrFail($id);
$exchange->balance = ['your', 'values', 'as', 'an', 'array'];
$exchange->save();
Sign up to request clarification or add additional context in comments.

Comments

2

You can remove the cast and implement an accessor method on the Exchange model:

public function getBalanceAttribute($value)
{
    return json_decode($value);
}

And consume normally like you want:

foreach($exchanges as $ex)
   echo gettype($ex->balance)
endforeach

3 Comments

If I use the accessor method it returns an Object, not an array?
I like this approach. I feel it gives you better flexibility with the data. You can even add the setBalanceAttribute method to json_encode your value.
@eskimo Try using json_decode($value, true) to return an array instead of an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.