Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now

Laravel 10 Store JSON in Database Example ?

In this tutorial we’re going to learn how to store JSON data in Database in Laravel

What is JSON ?

JSON (JavaScript Object Notation) is a lightweight, text-based format for data exchange that is easy for humans to read and write and easy for machines to parse and generate. JSON is a popular data format used in web applications, APIs, and data exchange between systems. JSON data is represented as key-value pairs and uses a syntax similar to JavaScript object literals. Each key-value pair is separated by a comma and enclosed in curly braces 

Step 1: Install Laravel

Use Below command for installation

composer create-project laravel/laravel example-app

Step 2: Create Migration

php artisan make:migration create_items_table

Next go to migration file and put below code

<?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(): void
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->json('data')->nullable();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('items');
    }
};

Then run migration command to create items table.

php artisan migrate

Next to create migration file

php artisan make:model Item

Next go to model and put below code

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class Item extends Model
{
    use HasFactory;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = [
        'title', 'data' 
    ]; 
  
    /**
     * Get the user's first name.
     *
     * @return \Illuminate\Database\Eloquent\Casts\Attribute
     */
    protected function data(): Attribute
    {
        return Attribute::make(
            get: fn ($value) => json_decode($value, true),
            set: fn ($value) => json_encode($value),
        );
    } 
}

Next got to web.php and put below code

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ItemController;
   
/*
|--------------------------------------------------------------------------
| 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('item', [ItemController::class, 'index']);

Next go to Controller file and put below code

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Item;
  
class ItemController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $input = [
            'title' => 'Demo Title',
            'data' => [
                '1' => 'One',
                '2' => 'Two',
                '3' => 'Three'
            ]
        ];
  
        $item = Item::create($input);
  
        dd($item->data);
  
    }
}

Now run the project

php artisan serve

Open this url

http://127.0.0.1:8000/item

Output:-

Now data store successfully.

Hi I am Amit Kumar Thakur Experienced as s Software Developer with a demonstrated history of working in the information technology and services industry. Skilled in HTML, CSS, Bootstrap4, PHP, Laravel-9 , REST API,FB API,Google API, Youtube Api, Bitbucket,Github,Linux and jQuery. Strong engineering professional focused in Computer/Information Technology Administration and Management. Currently my profile is to Software Developer, analyze the requirement, creating frame for web application, coding and maintenance.

Related Posts

How to Crawl any website Meta Title and Meta Description in Laravel ?

1st step install below package. Next to create Controller First go to route and put below code Next go to controller and put below code Next go…

SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into `oauth_clients` (`user_id`, `name`, `secret`

In this tutorial i’m going to solve the error SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into oauth_clients (user_id, name, secret Error :-…

Top 20 Laravel Interview Question in 2024

In this tutorial im going share interview experience For laravel developer. A list of top frequently asked Laravel Interview Questions and answers are given below. Q #1) What is…

How to Get Google Analytics API key ?

In this tutorial we’re going to share how to get the google Analytics API key. I have shared in very easy way. First go enable Google analytics…

Youtube Subscriber Count in ReactJs

In this tutorial i’m going to learn how to count YouTube Subsribers count, views count as well, as define below. In order to install your app, first…

How to Disable Laravel’s Eloquent timestamps in laravel ?

In this tutorial we’re going to share how to disable the automatic created_at and updated_at timestamps in Laravel’s Eloquent models, along with explanations of different scenarios: 1st…

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Laravel 10 Store JSON in Database Example ? […]

1
0
Would love your thoughts, please comment.x
()
x