For Laravel store JSON data in a database, you can use the Eloquent ORM and leverage the json column type available in most popular databases. In Laravel, you can easily store JSON data in a database by converting the JSON data to a string and then storing it in a database column. Here’s a step-by-step guide on how to store JSON data in the database using Laravel.
How to Store JSON Data in Laravel 10
Below Steps to follow on how to insert json data into database using laravel.
- Step 1: Download Laravel App
- Step 2: Setup Database
- Step 3: Generate migration and model
- Step 4: Add Routes
- Step 5: Create the controller
- Step 6: Create blade view File
- Step 7: Start your Application
Download Laravel App
First, we need to run the below command to download or install a fresh laravel setup. So open the terminal and run the following command:
composer create-project --prefer-dist laravel/laravel LaravelJson
Configure your Database
In this step, we need to our project root directory and open .env file. Then add database detail like the below:
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
Create Model & migration
Start by creating a migration to define the table structure. Open your terminal and run the following command to create a new migration file:
php artisan make:model Post -m
This command will generate a new migration file in the database/migrations directory. Open the migration file and define the table structure, including a json column to store the JSON data. Here’s an example:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->json('data')->nullable();
$table->timestamps();
});
}
Open the model app/Models/Post.php file and make sure to include the data column in the $fillable property, which allows mass assignment.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'data',
];
}
Run the migration command to create the database table.
php artisan migrate
Make Routes
Open the routes/web.php file, in here; you have to define the following route.
Route::get('/post', 'PostController@index');
Route::post('/post', 'PostController@store');
Create Controller
You need to create the Post controller using the following command:
php artisan make:controller PostController
Open and update the below code in app\Http\Controllers\PostController.php:
<?php
namespace App\Http\Controllers;
use App\Post;
use Redirect,Response;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return view('create');
}
public function store(Request $request)
{
$data = json_encode($request->all());
Post::create($data);
return back()->with('success', 'Data successfully store in json format.');
}
}
Create Blade view
Now create a blade view name create.blade.php let go to resources/views and put the below code on 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</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</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 method="post" action="{{url('post')}}">
@csrf
<div class="form-group">
<label for="Title">Title</label>
<input type="text" name="title" class="form-control" placeholder="Enter Title">
</div>
<div class="form-group">
<label for="description">Mobile Number</label>
<input type="text" name="description" class="form-control" id="description" placeholder="Enter Description">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>
Start your application
Now start the development server using running the below command.
php artisan serve
Now you are ready to run our laravel JSON data stored to the database example so run the below command to quick run.
http://localhost:8000/
That’s it! You have learned how to store JSON data in a database in Laravel 10. The json column type allows you to store and retrieve JSON data as needed, providing flexibility in working with structured data.
Copy pasting all the code, it gives this error:
Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, string given, called in /home/vagrant/code/formprova/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php on line 23
Pls fix this
Hi, There can you please update what you are sending from frontend to your controller then we can help you.
Yes Same error
Data is uploding but it showing NULL how can I get the Json file??
helloo how can i store json data using api in laravel ?
$data = json_encode($request->all());
Post::create($data);
If your table has one column is json (tags column)
Post::create([
‘title’ => $request->title,
‘tags’ => json_encode($request->tags)
]);