Laravel get JSON array from database

Viewed 46

What is the best way in Laravel to store an array in your database? And how do I get the same array with a query?

I have a variable that's an array in an array:

$colors = array(array('green'), array('yellow', 'white'));

When I store $colors, my database (column type = json) save it as:

[["green"], ["yellow", "white"]]

But when I try to get it from a query, I couldn't get the same array as $colors.

My query:

$colors = DB::table('colors')
          ->where('id', '1')
          ->value('arraycolors');

I hope someone can help how to query an array. Thanks a lot!

1 Answers

You don't need to convert the array data to a JSON string yourself, use the Laravel $casts parameter on your model: https://laravel.com/docs/9.x/eloquent-mutators#array-and-json-casting

You should do something like this in your model:

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

And I recommend changing your migration to text instead of json column like so:

$table->text('colors')->nullable();
Related