Laravel casting JSON to array?
Ad
I'm trying to convert the a JSON field to array. For example the model is like this:
protected $casts = [
'content' => 'array'
];
While in insert the content inside, I do it like this:
'content'=> json_encode([
'description' => $faker->paragraph(3),
'about' => $faker->paragraph(2),
'info' => $faker->paragraph(2),
'updated' => $faker->dateTimeBetween('-1 years', 'now')
]),
But while getting the data it prints a string, nothing else.
The migration in this part looks like this:
$campaign->json('content');
Sample of the output:
"content": "{\"description\":\"Ut quas quo odio illo. Voluptates quia fuga itaque sint. Velit sapiente fugit ea ut ducimus sint tempora eligendi. Ea et molestiae consequuntur quibusdam soluta voluptatem.\",\"about\":\"Aut voluptates et iste ut perspiciatis. Esse sunt ullam inventore sit doloremque et quisquam.\",\"info\":\"Corrupti et facere exercitationem consequatur aspernatur quo saepe. Omnis et tempore enim ut. Quia magnam quia enim et eos enim.\",\"updated\":{\"date\":\"2015-11-22 08:25:13.000000\",\"timezone_type\":3,\"timezone\":\"UTC\"}}",
Any ideas why?
Ad
Answer
Ad
When you define array
cast you don't need to do any json_encode
or json_decode
. When you want to insert, simple you need to do:
'content'=> [
'description' => $faker->paragraph(3),
'about' => $faker->paragraph(2),
'info' => $faker->paragraph(2),
'updated' => $faker->dateTimeBetween('-1 years', 'now')
],
Laravel will do the rest
And when you want to get content
field data, you simple need to use:
$campaign->content;
and you will have here array, so if you want to display description, you simple need to do:
echo $campaign->content['description'];
Ad
source: stackoverflow.com
Related Questions
Ad
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad