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
Laravel 8 Custom Email Verification Tutorial
Laravel 8 Custom Email Verific...

In this article, we will see an example of laravel 8 custom email verification. Many web applications require users...

Read More

Dec-29-2021

Copy To Clipboard JQuery
Copy To Clipboard JQuery

In this article, we will see how to copy to clipboard jQuery. we will learn how to copy text from textarea&nbs...

Read More

Aug-19-2020

How To Add Tooltip In React JS
How To Add Tooltip In React JS

In this article, we will see how to add a tooltip in react js. Tooltips display informative text when users hover o...

Read More

Sep-12-2022

How To Remove Spaces Using JQuery
How To Remove Spaces Using JQu...

In this article, we will explain to you how to remove extra space using jquery. many times we have requirements to...

Read More

Aug-10-2020