How to Store Array in Database Laravel 10 - TechvBlogs

How to Store Array in Database Laravel 10

Learn how to efficiently store arrays in your Laravel 10 database with our step-by-step guide.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

7 months ago

TechvBlogs - Google News

In this article, you'll uncover a step-by-step guide on storing arrays in a Laravel database. Explore how to efficiently save array data in a database using Laravel, benefiting from a clear and concise explanation of the process.

This example is compatible with Laravel versions 6, 7, 8, 9, and 10, ensuring flexibility and functionality across multiple Laravel releases.

In scenarios where extensive data or variable column structures make it impractical to add numerous nullable fields to a database table, the JSON data type becomes indispensable. To illustrate how to store and retrieve a JSON array within a Laravel database, I'll provide you with a simple and effective example for handling JSON data storage.

In this example, our initial step involves creating a migration that includes a JSON column. Subsequently, we'll generate a model equipped with both getter and setter methods. This configuration allows you to create records by passing data as an array and retrieve records in the form of an array. Let's delve into this straightforward example to gain a better understanding.

Step 1 - Install Laravel

While optional, if you haven't already created the Laravel app, you can proceed by executing the following command:

composer create-project laravel/laravel example-app	

Step 3 - Create Migration

In this step, our objective is to create a database migration for the items table, featuring title and data (JSON Column) columns. Additionally, we'll generate a model for the items table to facilitate our data management.

php artisan make:migration create_items_table

database/migrations/2023_09_05_563219_create_items_table.php

<?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()
    {
        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()
    {
        Schema::dropIfExists('items');
    }
};

Then run migration command to create items table.

php artisan migrate

Step 3 - Create Model

In this phase, we will craft the Item.php model, complete with the necessary getter and setter methods. Let's proceed to create the model and enhance the following code:

php artisan make:model Item

App/Models/Item.php

<?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),
        );
    } 
}

Step 4 - Create Route

In this step, we'll establish a route for testing purposes. Let's go ahead and create this route:

routes/web.php

<?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']);

Step 5 - Create Controller

For this next step, we'll create the ItemController.php file and implement the 'index()' method. This method will be responsible for creating item records using arrays and accessing them as arrays.

app/Http/Controllers/ItemController.php

<?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);
  
    }
}

Run Laravel App:

With all the necessary steps completed, you can now enter the following command and press Enter to execute the Laravel app:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the app:

http://localhost:8000/item

You can observe the database output and display the variable output as follows:

Output:

array:3 [
  1 => "One",
  2 => "Two",
  3 => "Three"
]

Thank you for reading this article!

Comments (0)

Comment


Note: All Input Fields are required.