Laravel 10 How To Insert Array Data in Table Column Example

Reading Time: 6 minutes
594 Views

Array data handling and inserting into a database table column is a common necessity in web development. Using Laravel 10’s Eloquent ORM, you can execute this work quickly. This tutorial will walk you through the steps of putting array data into a table column in Laravel 10.

There are numerous circumstances in which you may need to insert an array of data into a table column, such as storing multiple values or dealing with linked entries. Eloquent ORM from Laravel streamlines this procedure by allowing you to work with arrays and database columns smoothly.

Read More: Laravel 10 Dynamic Dependent Dropdown Using Ajax Example

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Table Migration

We will create a migration file for items table. Open project into terminal and run this command.

$ php artisan make:migration create_items_table

It will create a migration file 2023_09_07_110040_create_items_table.php inside /database/migrations folder.

Read More: Laravel 10 Submit Livewire Form Data Tutorial

Open migration file and write this code into it.

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->json('data')->nullable();
            $table->timestamps();
        });
    }

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

Run Migration

Next,

To migrate migration so that we create the schema of items table inside database.

$ php artisan migrate

It will create items table.

Setup Model

Open project terminal and run this artisan command to create model.

$ php artisan make:model Item

It will create a file Item.php inside /app/Models folder.

Open Item.php and write this code into it.

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

    protected $fillable = [
        'title', 'data'
    ];

    /**
     * @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),
        );
    }
}

Concept

Here, this is the concept of laravel model known as get and set method blocks. While processing data input these methods will be used.

get: fn ($value) will be used when we fetch data from database table. Automatically it will process the incoming data from db.

set: fn ($value) will be used when we save data into database.

protected function data(): Attribute
{
    return Attribute::make(
        get: fn ($value) => json_decode($value, true),
        set: fn ($value) => json_encode($value),
    );
}

Here, before data save -> json_encode() will be used. And when data get from database json_decode() will be used.

Read More: How To Create RSS Feed in Laravel 10 Example Tutorial

Next,

Create Controller

Back to project terminal and run this command,

$ php artisan make:controller ItemController

It will create ItemController.php file inside /app/Http/Controllers folder.

Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

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

class ItemController extends Controller
{
    public function index()
    {
        $input = [
            'title' => 'Sample Title',
            'data' => [
                '1' => 'First',
                '2' => 'Second',
                '3' => 'Third'
            ]
        ];

        $item = Item::create($input);

        dd($item->data);
    }
}

You can see, we are creating an item with title (a string value) and data (an array of values).

Add Route

Open web.php file from /routes folder. Add this route into it.

//...
use App\Http\Controllers\ItemController;

Route::get('item', [ItemController::class, 'index']);

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/item

Once you hit this URL, your data will be saved into database into encoded format and also will get outputted in decoded format.

Read More: Laravel 10 Auth with Livewire Jetstream Tutorial

Database table will look like this –

We hope this article helped you to learn Laravel 10 How To Insert Array Data in Table Column Example in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.