Laravel Store/Save JSON Data in Mysql Database Example

If you are working with json and want to store or save in a mysql database using laravel apps. So, in this tutorial guide, you will learn how to store/save/insert JSON data in MySQL using Laravel.

As well as how to convert string data into JSON format data and how to insert JSON data into MySQL using laravel.

Laravel Insert/Save/Store JSON Format Data in Database

Using the following steps, you will learn how to store/insert/save your JSON format data in MySQL database using laravel:

  • Step 1: Install Laravel Latest Setup
  • Step 2: Setup Database
  • Step 3: Generate migration and model
  • Step 4: Migrate Database
  • Step 5: Add Route
  • Step 6: Create controller
  • Step 7: Create blade view
  • Step 8: Start Development Server

Step 1: Install Laravel Latest Setup

First of all, you need to download laravel fresh setup name Laravel Json to insert or store data into laravel DB app. So, use the below command and download fresh new laravel setup:

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

Step 2: Setup Database

In this step, add the database details in the .env file. So Navigate to your project root directory and open .env file. Then set up database credential into it:

 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: Migrate Database

Before you run php artisan migrate command go to app/providers/AppServiceProvider.php and update the below code into AppServiceProvider.php file:

 
use Illuminate\Support\Facades\Schema;

function boot()
{
Schema::defaultStringLength(191);
}

Step 4: Generate migration and model

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->string('token')->nullable();
            $table->text('data')->nullable();
            $table->timestamps();
        });
    }

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 5: Add Route

In this step, you need to create two routes in web.php file one is the display form and the second route is storing/saving data in JSON to the MySQL database. Go to app/routes/web.php file and create the below routes here :

  use App\Http\Controllers\JsonController;

  Route::get('laravel-json', [JsonController::class, 'index']);
  Route::post('store-json', [JsonController::class, 'store']);

Step 6: Create a Controller

In this step, you need to create one controller named JsonController.php. So use the below command and create a controller :

php artisan make:controller JsonController 

After successfully creating the controller go to app/http/controllers open JsonController and create two methods

Here, The first method displays the form and the second method convert Laravel string form data to JSON format and saves it to the database:

Note that, if you are using Laravel > 8.x version, you should use Model on your controller file like this:

use App\Models\Test;

Or if you are using a lower version like 7. x, 6.x, 5. x of Laravel, so you should use Model on your controller file like this:

use App\Test;
<?php

namespace App\Http\Controllers;
use Redirect,Response;
use Illuminate\Http\Request;

class JsonController extends Controller
{
   public function index()
   {
      return view('json_form');
   }

  public function store(Request $request)
  {
      $data = $request->only('name','email','mobile_number');
      $test['token'] = time();
      $test['data'] = json_encode($data);
      Test::insert($test);
      return Redirect::to("laravel-json")->withSuccess('Great! Successfully store data in json format in datbase');
  }

}

Step 7: Create a Blade view

In this step, you need to create one blade view name json.blade.php let go to resources/views and create one blade view file.

After creating the blade view file put the below code here :

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Laravel Store Data To Json Format In Database - Tutsmake.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <style>
   .error{ color:red; }
  </style>
</head>

<body>

<div class="container">
    <h2 style="margin-top: 10px;">Laravel Store Data To Json Format In Database - Tutsmake.com</h2>
    <br>
    <br>

    @if ($message = Session::get('success'))
    <div class="alert alert-success alert-block">
        <button type="button" class="close" data-dismiss="alert">×</button>
          <strong>{{ $message }}</strong>
    </div>
    <br>
    @endif

    <form id="laravel_json" method="post" action="{{url('store-json')}}">
      @csrf
      <div class="form-group">
        <label for="formGroupExampleInput">Name</label>
        <input type="text" name="name" class="form-control" id="formGroupExampleInput" placeholder="Please enter name">
      </div>
      <div class="form-group">
        <label for="email">Email Id</label>
        <input type="text" name="email" class="form-control" id="email" placeholder="Please enter email id">
      </div>
      <div class="form-group">
        <label for="mobile_number">Mobile Number</label>
        <input type="text" name="mobile_number" class="form-control" id="mobile_number" placeholder="Please enter mobile number">
      </div>
      <div class="form-group">
       <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </form>

</div>

</body>
</html>

Step 8: Start Development Server

Finally, Run the following command to start the development server. So use the php artisan serve command and start your server :

 php artisan serve

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

 php artisan serve --port=8080  

Now you are ready to run our laravel JSON data stored to database example so run below command to quick run.

 http://localhost:8000/
Or direct hit in your browser
http://localhost/LaravelJson/public

Conclusion

In this laravel tutorial for storing JSON data in the database, you have successfully laravel project stored data in JSON format in our database. our examples run quickly.

The Laravel Store Json example look like this :

Recommended Laravel Posts

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.

One reply to Laravel Store/Save JSON Data in Mysql Database Example

Leave a Reply

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