How to store json code in database table column in laravel?

Member

by lily , in category: PHP Frameworks , 5 months ago

How to store json code in database table column in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , a month ago

@lily 

In Laravel, you can store JSON data in a database table column by using the json data type for the column in the database migration file. Here's how you can do it:

  1. Create a new migration file using the following artisan command:
1
php artisan make:migration add_json_column_to_table --table=your_table_name


  1. Open the newly created migration file located in the database/migrations directory and add the following code to define a json type column in the database table:
1
2
3
4
5
6
public function up()
{
    Schema::table('your_table_name', function (Blueprint $table) {
        $table->json('json_column')->nullable();
    });
}


  1. Run the migration to update the database schema by using the following artisan command:
1
php artisan migrate


  1. Now, to store JSON data in the json_column column of the your_table_name table, you can use Eloquent models to insert or update records. Here's an example of how to store JSON data in the column:
1
2
3
4
5
6
7
use AppModelsYourModel;

$data = ['key1' => 'value1', 'key2' => 'value2']; // JSON data

$yourModel = YourModel::create([
    'json_column' => json_encode($data)
]);


  1. To retrieve and work with the JSON data stored in the column, you can use Laravel's JSON casting feature for Eloquent models. Add the following code to your Eloquent model to cast the json_column data into an array automatically:
1
2
3
4
5
6
class YourModel extends Model
{
    protected $casts = [
        'json_column' => 'array',
    ];
}


Now you can access and manipulate the JSON data as an array in your application.