JSON encode and decode example in laravel

JSON Encode and Decode in Laravel

In this tutorial, I will give you an example of JSON Encode and Decode in Laravel, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 application.

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

JSON encode and decode example in laravel

save multiple columns data into single columns using JSON in laravel

JSON decode in the blade file in laravel

What is JSON

JSON stands for JavaScript Object Notation and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server and used as a data format by any programming language.

Need of JSON Encode and Decode in Laravel

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 in 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 in 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 in the database table in the Laravel application.

Let’s see an example:-

Generating Migration with Model :

php artisan make:model JsonExample -m

Migration Structures :

<?php

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

class CreateJsonExamplesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('json_examples', function (Blueprint $table) {
            $table->id();
            $table->text('student_details');
            $table->timestamps();
        });
    }

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

Run Migration :

php artisan migrate

app\Models\JsonExample.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class JsonExample extends Model
{
    use HasFactory;
}

Create a Controller :

php artisan make:controller JsonExampleController

routes\web.php :

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\JsonExampleController;

/*
|--------------------------------------------------------------------------
| 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!
|
*/

#JSON Encode and Decode Example
Route::get('/add-student', [JsonExampleController::class, 'addStudent']);
Route::post('/store-student', [JsonExampleController::class, 'storeStudent'])->name('student.store');
Route::get('/list-student', [JsonExampleController::class, 'listStudent']);

Related article : Save Multiple Columns Data into Single Column in Laravel.

app\Http\Controllers\JsonExampleController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\JsonExample;

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

    public function storeStudent(Request $request){
        $data = new JsonExample();
        $data->student_details = json_encode(
            ['stu_name'  => $request->name,
            'stu_dob'    => $request->dob,
            'stu_class'  => $request->class,
            'stu_roll_no'=> $request->roll_number,
            'stu_phone'  => $request->phone,
            'stu_email'  => $request->email,
            'stu_address'=> $request->address
        ]);
        $data->save();
        dd('success!, Student add successfully.');
    }

    public function listStudent(){
        $data = JsonExample::get();
        return view('jsonexample.list',compact('data'));
    }
}

resources\views\jsonexample\create.blade.php :

encode values in JSON format in laravel
<main>
	<div class="container">
		<div class="row justify-content-center">
			<div class="col-lg-6">
				<div class="main">
					<h4><a>JSON Encode and Decode in Laravel-Example</a></h4>
					<form role="form" action="{{route('student.store')}}" method="post"> @csrf
						<div class="row">
							<div class="form-group col-md-6">
								<label>Student name <span class="text-danger">*</span></label>
								<input type="text" name="name" class="form-control"> </div>
							<div class="form-group col-md-6">
								<label>Student D.O.B <span class="text-danger">*</span></label>
								<input type="date" name="dob" class="form-control"> </div>
							<div class="form-group col-md-6">
								<label>Student Class<span class="text-danger">*</span></label>
								<input type="text" name="class" class="form-control"> </div>
							<div class="form-group col-md-6">
								<label>Student Roll.no <span class="text-danger">*</span></label>
								<input type="text" name="roll_number" class="form-control"> </div>
							<div class="form-group col-md-6">
								<label>Student phone <span class="text-danger">*</span></label>
								<input type="text" name="phone" class="form-control"> </div>
							<div class="form-group col-md-6">
								<label>Student email <span class="text-danger">*</span></label>
								<input type="text" name="email" class="form-control"> </div>
						</div>
						<div class="form-group">
							<label>Student address <span class="text-danger">*</span></label>
							<textarea name="address" class="form-control" rows="4" cols="50"></textarea>
						</div>
						<div class="form-group">
							<button type="submit" class="btn btn btn-secondary"> save </button>
					</form>
					</div>
				</div>
			</div>
		</div>
</main>

resources\views\jsonexample\list.blade.php :

decode values in JSON format in laravel
      <div class="container">
         <h3 style="color: #BE206B;">JSON Encode and Decode in Laravel-Example</h3>
         <br>
         <table class="table table-bordered">
            <tr>
               <th>ID</th>
               <th>Name</th>
               <th>Dob</th>
               <th>Class</th>
               <th>Roll no</th>
               <th>Phone</th>
               <th>Email</th>
               <th>Address</th>
            </tr>
            @foreach ($data as $key => $data )
            <tr>
               <td>{{ $key+1 }}</td>
               @php $json_data = json_decode($data->student_details,true); @endphp
               <td>{{ $json_data['stu_name'] }}</td>
               <td>{{ $json_data['stu_dob'] }}</td>
               <td>{{ $json_data['stu_class'] }}</td>
               <td>{{ $json_data['stu_roll_no'] }}</td>
               <td>{{ $json_data['stu_phone'] }}</td>
               <td>{{ $json_data['stu_email'] }}</td>
               <td>{{ $json_data['stu_address'] }}</td>
            </tr>
            @endforeach
         </table>
      </div>

Run application :

http://127.0.0.1:8000/add-student

In this article, we learned “JSON Encode and Decode example in Laravel”, I hope this article will help you with your Laravel application Project.

Read also-: How to validate array values in Laravel.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com