Home Laravel How to Store Array in Database Laravel?

How to Store Array in Database Laravel?

by Shahriar Sagor

Today now in this tutorial, i will show you how to store array in database laravel application. Here I will explained this simply example step by step laravel store array in database. So here i will show you how to store array data in database in laravel application. Now I will explained this very simply about how to store array in database laravel.

We can also use this example with laravel 6, laravel 7, laravel 8 and laravel 9 any version.

Sometimes, if we have any large data or unfixed columns then we can not create the too many fields in a database table also with the nullable field. So we need to use JSON data type to store the values, on that way we can easily store large data or unstructured data. If we want to store the JSON array in a database in laravel. Then here I will give you a very simple example of how to store a JSON array store and access it from the database in laravel.

Now in this example, first, i will create the migration with a JSON column. Then i will create a model with a getter and setter. When i create the records then i can pass them as an array and when i will get records then i will find an array. So let’s see a simple example and learn it.

Step 1: Install Laravel

At first of all we have to get the fresh Laravel version application by using the bellow command. So open your terminal OR command prompt and then run the bellow command:

composer create-project laravel/laravel example-app

Step 2: Create Migration

Here, i have to create database migration for “items” table with title and data(JSON Column) columns and also i will create the model for items table.

php artisan make:migration create_items_table

database/migrations/2022_08_15_141714_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 need to run migration command to create items table.

php artisan migrate
Step 3: Create Model

Now in this step, i will create Item.php model with getter setter. Let’s create the model and update 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

Now in this step, i will create one route for testing. So just create one route here.

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

Now in this step, i will create the ItemController file and write index() method to create the item records with array and access as array.

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:

All the needed steps have been done, now we have to type the given in the below command and then hit enter to run the Laravel application:

php artisan serve

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like