Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Save Multiple Columns Data into Single Column in Laravel

Save Multiple Columns Data into Single Column in Laravel

In this tutorial, I will give you an example of How to Save Multiple Columns Data into Single Column in Laravel, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

We have a form and there are Four fields product name, product type, product price, and product description. We save the Three fields values in JSON format in a single column name product_details,

So that we can retrieve them later in the view blade file in our Laravel application Project.

Save Multiple Columns Data into Single Column in Laravel
Save Multiple Columns Data into Single Column in Laravel

Inserting Multiple Text Field Data into a Single Column

Sometimes we have more columns in our table in the database, and we don’t want to create a new table for storing the related data into the other table on behalf of a primary key.

So, we have simple or easiest options to store multiple text field data into a single column as a JSON format.

We simply store all of the request parameters into a single variable as an associative array in the pair of keys and values and store it in JSON Format we just use JSON Encode and Decode.

Generating Migration :

php artisan make:migration create_tests_table

Migration Structure :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tests', function (Blueprint $table) {
            $table->id();
            $table->string('product_name');
            $table->longText('product_details');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tests');
    }
}

Run Migration :

php artisan:migrate
Save Multiple Columns Data into Single Column in Laravel

Create Model :

php artisan make:model Model/Test

App\Model\CustomSlugExample

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    protected $table = 'tests';
}

Create Routes :

routes\web.php

#Example of Store Multiple Field Data into Single Column
Route::get('add-data','TestController@create')->name('create.data');
Route::get('list-data','TestController@ListData')->name('list.data');
Route::post('store-data','TestController@StoreData')->name('store.data');
Route::get('view-data/{id}','TestController@ViewData')->name('view.data');


Create Controller :

php artisan make:controller TestController

App\Http\Controllers\CustomSlugExampleController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Test;

class TestController extends Controller
{
    public function create(){
        return view('jsonexample.create');
    }

    public function ListData(){
     $data = Test::orderBy('id','desc')->get();
     return view('jsonexample.list',compact('data'));
    }

    public function StoreData(Request $request){
        $data = new Test();
        $data->product_name = $request->product_name;
        $data->product_details = json_encode(['ProductType'=>$request->product_type,'ProductPrice'=>$request->product_price,'ProductDescription'=>$request->product_description]);
        $data->save();
        return redirect()->back();
    }

    public function ViewData($id){
       $data = Test::where('id',$id)->first(); 
       return view('jsonexample.view',compact('data'));
    }
}

Create Blade Files :

resources\views\jsonexample\create.blade.php

Save Multiple Columns Data into Single Column in Laravel
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Save Multiple Columns Data into Single Column in Laravel</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
        <br>
         <h3>Laravel - Save Multiple Columns Data into Single Column in Database</h3>
         <a class="btn btn-primary" href="{{route('list.data')}}" role="button">Product List</a>
         <br>
         <br>
         <div class="card">
            <form method="post" action="{{route('store.data')}}">
               @csrf
               <div class="card-header">Please fill up all the Field's.</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="Product Name">Product Name :</label>
                        <input type="text" class="form-control" placeholder="Enter Product name" name="product_name" required>
                     </div>
                      <div class="col-md-6">
                        <label for="Product Type">Product Type :</label>
                        <input type="text" class="form-control" placeholder="Enter Product type" name="product_type" required>
                     </div>
                      <div class="col-md-6">
                        <label for="Product Price">Product Price :</label>
                        <input type="text" class="form-control" placeholder="Enter Product price" name="product_price" required>
                     </div>
                      <div class="col-md-6">
                        <label for="Product Description">Product Short Description :</label>
                        <input type="text" class="form-control" placeholder="Enter Product description" name="product_description" required>
                     </div>
                     
                  </div>
               </div>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
               <br/>
         </div>
         </form>
      </div>
   </body>
</html>

resources\views\jsonexample\list.blade.php

Save Multiple Columns Data into Single Column in Laravel
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Save Multiple Columns Data into Single Column in Laravel</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h3>Product List Data</h3>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Product Name</th>
                  <th>Action</th>

               </tr>
            </thead>
            <tbody>
               @foreach($data as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{$data->product_name}}</td>
                  <td>
                  <a href="{{route('view.data',$data->id)}}">View</a>
                </td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>
   </body>
</html>

resources\views\jsonexample\view.blade.php

Save Multiple Columns Data into Single Column in Laravel
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Save Multiple Columns Data into Single Column in Laravel</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
        <br>
         <h3>Laravel - Save Multiple Columns Data into Single Column in Database</h3>
         <br>
         <div class="card">
            <form>
               <div class="card-header">View Data</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="Product Name">Product Name :</label>
                        <input type="text" class="form-control" value="{{$data->product_name}}">
                     </div>

                      @php $json_data = json_decode($data->product_details,true); @endphp
                      
                      <div class="col-md-6">
                        <label for="Product Type">Product Type :</label>
                        <input type="text" class="form-control" value="{{$json_data['ProductType']}}">
                     </div>
                      <div class="col-md-6">
                        <label for="Product Price">Product Price :</label>
                        <input type="text" class="form-control" value="{{$json_data['ProductPrice']}}">
                     </div>
                      <div class="col-md-6">
                        <label for="Product Description">Product Short Description :</label>
                        <input type="text" class="form-control" value="{{$json_data['ProductDescription']}}">
                     </div>
                     
                  </div>
               </div>
              <div class="col-md-3"> 
                  &nbsp;<a href="{{route('list.data')}}">Go Back</a>
               </div>
               <br/>
         </div>
         </form>
      </div>
   </body>
</html>

In this article, we learned Save Multiple Columns Data into Single Column in Laravel, I hope this article will help you with your Laravel application Project.

Read Also : How to pass multiple parameters in url laravel.