How to Store array in Laravel Database as JSON
Storing an array type in the Laravel Database is not possible using migrations, because the framework does not offer the type array, so how we can do that?
Adding the migration
Here we have a simple migration of posts table and we want to add an array of tags to each post, so we create the tags column as JSON.
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->json('tags');
$table->timestamps();
});
}
Using laravel $casts property
Next in your Post model use the Laravel $casts property so that when you fetch data from the database the tags column will be converted to an array.
protected $casts = [
'tags' => 'array'
];