Laravel 10 Store JSON Data In Database Example

In this article, we will see laravel 10 store JSON data in the database example. Here, we will learn about how to store JSON data in the database in laravel 11. JSON (JavaScript Object Notation) is a lightweight, text-based format for data exchange that is easy for humans to read and write and easy for machines to parse and generate.

JSON is a popular data format used in web applications, APIs, and data exchange between systems. JSON data is represented as key-value pairs and uses a syntax similar to JavaScript object literals.

In this laravel 11, you can store JSON data in MySQL.

Each key-value pair is separated by a comma and enclosed in curly braces {}. Keys are always strings, while values can be strings, numbers, boolean values, arrays, or nested JSON objects.

So, let's see how to store JSON data in the database in laravel 10, laravel 11 stores JSON in the database, and how to store JSON data in MySQL using laravel 10/11.

Step 1: Install Laravel 10/11

In this step, we will install 10 using the following command.

composer create-project laravel/laravel laravel-10-json-example

 

 

Step 2: Create Migration

Then, we will create a migration for the posts table. In this table, we will add the title and data column. The data column type is JSON.

php artisan make:migration create_posts_table

Migration: 

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->json('data')->nullable();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

Now, migrate the table in the database using the following command.

php artisan migrate

 

 

Step 3: Create Model

Now, we will create the Post.php model using the following command. Also, we will use the get and set function.

php artisan make:model Post

app/Models/Post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class Post extends Model
{
    use HasFactory;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'data' 
    ]; 
  
    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function data(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => json_decode($value, true),
            set: fn ($value) => json_encode($value),
        );
    } 
}
 
Step 4: Add Route

Then, we will add routes in the web.php file. So, add the following code to that file.

routes/web.php

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
   
/*
|--------------------------------------------------------------------------
| 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::get('index', [PostController::class, 'index']);

 

 

Step 5: Create Controller

Now, we will create the PostController.php file. In this file, we will add the index() function. In the index() function, we will add JSON data and it can be stored in the database.

app/Http/Controllers/PostController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $input = [
            'title' => 'Laravel 10 Store JSON Data In Database Example',
            'body' => [
                '1' => 'Store JSON Data',
                '2' => 'Insert JSON Data in MySQL Database',
                '3' => 'How to store JSON Data in Laravel 10'
            ]
        ];
  
        $post = Post::create($input);
  
        dd($post->data);
  
    }
}

Output:

array:3 [
    1 => "Store JSON Data"
    2 => "Insert JSON Data in MySQL Database"
    3 => "How to store JSON Data in Laravel 10"
]

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS