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
How To Check Password Strength Using JQuery
How To Check Password Strength...

In this article, we will see how to check password strength using jquery. here we will check whether password ...

Read More

Sep-04-2020

How To Validate Username And Password In React JS
How To Validate Username And P...

In this article, we will see how to validate username and password in react js. In this example, we will validate t...

Read More

Sep-13-2022

How to Build a Blog CMS with React JS?
How to Build a Blog CMS with R...

Are you a blogger who expresses his thoughts with the help of words? If yes, then you might have once thought to create...

Read More

Nov-13-2023

Laravel 8 Datatables Keeping Selected Page Number
Laravel 8 Datatables Keeping S...

In this tutorial we will see laravel 8 datatables keeping selected page number after callback. In datatable page nu...

Read More

Dec-03-2021