Laravel 10 Create Txt JSON File and Download Tutorial Example

Laravel 10 Create Txt JSON File and Download Tutorial Example

If you want to store or insert form data in JSON format in MySQL database in your Laravel applications. And also want to store and download the JSON data of the form by putting it in a JSON file.

So In this tutorial, you will learn how to save/insert JSON data to a txt file & MySQL database and download it from a text (txt) file.

Laravel 10 Create Txt JSON File and Download Tutorial Example

By using the following steps, you can store form data in JSON format in MySQL database in your Laravel application. And store and download the data of the form by putting it in a JSON file.

  • Step 1: Create New Laravel 10 Project
  • Step 2: Setup Database with Laravel Project
  • Step 3: Create Migration and Model File
  • Step 4: Run Migration
  • Step 5: Define Routes
  • Step 6: Create a Controller
  • Step 7: Create blade view
  • Step 8: Start Development Server

Step 1: Create New Laravel 10 Project

Firstly, Open your terminal and command prompt.

Then you need to execute the following command into it to download and install laravel 10 new project in your server:

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

Step 2: Setup Database with Laravel Project

Once you have installed laravel new project in your server. Now, you need to setup database with laravel project.

So, visit your project root directory and find .env file. Then setup database details like the following:

 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: Create Migration and Model File

In this step, you need to generate one migration and model name file.

So, execute the following command on cmd to create these files:

php artisan make:model Test -m

Once you have created the model and migration file by using the above-given command.

Now, you need to visit app/database/migration directory and find the migration file name create_tests_table.php. Then 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();
        });
    }

Step 4: Run Migration

Now, open again your terminal or command prompt.

Then execute the following mirgrtion command into it to create some tables in our database:

php artisan migrate

Step 5: Define Routes

In this step, you need to define two routes in the web.php file.

So, visit app/routes/ directory and open web.php file. Then define the following routes into it:

  use App\Http\Controllers\JsonController;


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

Step 6: Create a Controller

In this step, you need to create one controller named JsonController.php.

So execute the following command on command prompt or terminal to create a controller:

php artisan make:controller JsonController 

Once you have created controller by using the above given command. Then visit app/http/controllers directory and open JsonController.php file. And add the following methods into it:

<?php
namespace App\Http\Controllers;
use Redirect,Response;
use Illuminate\Http\Request;
use App\Models\Test;

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

  public function download(Request $request)
  {
      $data = $request->only('name','email','mobile_number');
      $test['token'] = time();
      $test['data'] = json_encode($data);
      Test::insert($test);
      $fileName = $test['token']. '_datafile.json';
      File::put(public_path('/upload/json/'.$fileName),$test);
      return download(public_path('/upload/jsonfile/'.$fileName));
  }

}

Note that:- The first method display the form and the second method convert Laravel string form data to json format and saves it to the database.

Step 7: Create a Blade view

In this step, you need to create one blade view name json.blade.php file. So, go to resources/views directory and create a blade view file then add the following code into it:

<!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('json-file-download')}}">
      @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, execute the following command on cmd or terminal to start the development 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 start your laravel app on browser by using the following URLs:

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

Conclusion

In this comprehensive Laravel tutorial, you will learn how to efficiently store JSON data in a database. By following the step-by-step instructions provided, you will successfully implement a Laravel project that stores data in JSON format within the database. The examples provided in this tutorial have been meticulously designed for optimal performance, ensuring that your code runs quickly and smoothly.

Throughout the tutorial, you will gain a solid understanding of the best practices and techniques for working with JSON data in Laravel. You will explore various approaches to handle JSON formatting and storage, allowing you to choose the most suitable method for your specific application requirements.

By the end of this tutorial, you will have the necessary skills and knowledge to confidently store JSON data in your Laravel project’s database. The lessons learned in this tutorial will enable you to efficiently manage and manipulate JSON data, ensuring the smooth operation of your application while maintaining excellent performance.

Recommended Laravel Posts

Recommended:- Laravel Try Catch

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

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 10 Create Txt JSON File and Download Tutorial Example

  1. in form action url, please replace ‘json-file-download’ instead of ‘store-json’.

Leave a Reply

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