Laravel 11|10 Store JSON Format Data in Database Tutorial

In Laravel 11, define $casts parameter on model to store, retrieve, and manipulate data in JSON format in a database. for this you can open your model and define 'attributes' => 'json' under the $casts property.

In this example guide, we will show you how to store, retrieve, and manipulate data in JSON format in a database using Laravel 11|10|9 app.

How to Save JSON Data in Database MySQL using Laravel 11|10|9

Steps to store, retrieve, and manipulate data in JSON format in laravel 11|10|9 database:

Step 1: Install Laravel Latest Setup

Simply open your terminal or cmd and type composer create-project --prefer-dist laravel/laravel LaravelJson to install laravel app into your system:

composer create-project --prefer-dist laravel/laravel LaravelJson

Step 2: Setup Database

Navigate to your laravel project root directory and open .env file, and add the database details; as follows:

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3: Create a Model and Migration

In this step, you need to generate one migration file with create one model name Test using the below command :

php artisan make:model Test -m

After creating the model and migration file. Go to app/database/migration and find the migration file name create_tests_table.php and update the following code into it:

   public function up()
    {
        Schema::create('tests', function (Blueprint $table) {
            $table->increments('id');
            $table->json('attributes');
            $table->timestamps();
        });
    }

Next, go to the app/models directory and open Test.php model and add the following code into it:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
    use HasFactory;
    protected $casts = [
        'attributes' => 'json',
    ];
}

Now you need to run the below command. It will create some tables in our database, so use the below command :

php artisan migrate

Step 4: Add Routes

To create routes for getting and storing json data as attribute with the help of routes, Go to the app/routes/web.php file and add the following routes into it:

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\JsonController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::post('store-json-data', [JsonController::class, 'storeJsonData']);
Route::get('get-json-data', [JsonController::class, 'retrieveJsonData']);

Step 5: Store and Get JSON Data on the Controller

To create one controller named JsonController.php, run the php artisan make:controller JsonController command on cmd or terminal:

php artisan make:controller JsonController 

Now go to app/http/controllers directory and open JsonController.php file in text editor.

1. To store JSON Data as an attribute in Database Table

Here is the example code to store data as json attribute in msyql database:

public function storeJsonData(Request $request)
{
    $test = new Test;
    $test->attributes = [
        'name' => 'tutsmake'
        'email' => '[email protected]',
        'mobile_number' => '9874563210'
    ];
    $test->save();
}

2. To get JSON Data as an attribute from Database Table

Here is the example code to get data as JSON attribute from msyql database:

public function retrieveJsonData(Request $request)
{
  $test = Test::find(1);
  $attributes = $test->attributes;
}

Step 6: Start Development Server

Finally, Run the php artisan server command on cmd or terminal to to start development server:

 php artisan serve

 If you want to run the project diffrent port so use this below command

 php artisan serve --port=8080  

To use http://localhost:8000/store-json-data with post method to save/store data as json attribute in database on laravel app:

http://localhost:8000/store-json-data

And use http://localhost:8000/retrieve-json-data with get method to fetch/retrieve data as json attribute from database on laravel app:

http://localhost:8000/get-json-data

Conclusion

That’s it; you have successfully how to store/save and get/retrieve data in JSON format from database. on laravel apps.

For reference: https://laravel.com/docs/eloquent-mutators#array-and-json-casting.

Recommended Laravel Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *