How To Store JSON Data In Database Laravel 9

Websolutionstuff | Sep-28-2022 | Categories : Laravel

In this article, we will see how to store JSON data in the database laravel 9. Laravel 9 stores JSON data in MySQL database. In this tutorial, we will learn how to store JSON data in MySQL using laravel 9 apps. Also, we will see how to convert string form data to JSON format data in the database using laravel 9.

JSON stands for JavaScript Object Notation. JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

So, let's see laravel 9 JSON data insert/stored in the MySQL database.

JSON Data Stored in MySQL Database in Laravel 9

Step 1: Install Laravel 9

Step 2: Create Migration

Step 3: Create Model

Step 4: Add Route

Step 5: Create Controller

 

Step 1: Install Laravel 9

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

composer create-project laravel/laravel laravel-9-app

 

 

Step 2: Create Migration

Now, we will create a migration for the posts table. And in this table, we will add the title and body column. The body column type is JSON.

php artisan make:migration create_posts_table
<?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()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->json('body')->nullable();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        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', 'body' 
    ]; 
  
    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function body(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => json_decode($value, true),
            set: fn ($value) => json_encode($value),
        );
    } 
}

 
Step 4: Add Route

In this step, we will add routes in the web.php 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. And in this, we will add the index() function. In the index() function we will add JSON data and it can store 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' => 'JSON Data Store in Database',
            'body' => [
                '1' => 'Store JSON Data',
                '2' => 'Insert JSON Data in MySQL',
                '3' => 'Laravel 9 JSON Data Store'
            ]
        ];
  
        $post = Post::create($input);
  
        dd($post->body);
  
    }
}

Output:

array:3 [
    1 => "Store JSON Data"
    2 => "Insert JSON Data in MySQL"
    3 => "Laravel 9 JSON Data Store"
]

 


You might also like :

Recommended Post
Featured Post
Date Range Filter In Datatable jQuery Example
Date Range Filter In Datatable...

In this article, we will see the date range filter in the datatable jquery example. Many times we required data of ...

Read More

Nov-14-2022

How to File Upload in Angular 17 Tutorial
How to File Upload in Angular...

In this article, we'll see how to file upload in the angular 17 tutorial. Here, we'll learn about file uplo...

Read More

Apr-03-2024

7+ Laravel Tips: Optimize Database Queries (2024)
7+ Laravel Tips: Optimize Data...

Hey there, fellow developers! If you've been navigating the intricate world of Laravel, you know that optimizing dat...

Read More

Jan-03-2024

Laravel 9 Vue JS CRUD Operation Example
Laravel 9 Vue JS CRUD Operatio...

In this article, we will see the laravel 9 vue js crud operation example. Here, we will learn how to create a vue 3...

Read More

Dec-07-2022