In this post, you will learn how to save an array in a Laravel database. I will demonstrated how to save an array datatype in a database step by step. Here's how to use Laravel to save array data in a database. I will explain in detail how to store an array in a Laravel database.
The example below is applicable with Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10 versions.
Why do we have to store array in database? sometimes we have large data then we can not create many fields in database table. In this case we can use JSON data type to store various values which means we can store unstructured data easily. We will give you examples how do we insert and store JSON array in database table with Laravel 10.
Firstly, we will create migration file with a JSON column. After then we create a model class with getter and setter, so we can create records.
Firstly, we are going to install Laravel project, incase you do not have, and run with command below.
composer create-project laravel/laravel blog
Important note: suppose you have configured connection databasae in .env file
We will create new database migration file for "books" table with title, author, and genre (JSON column) and then we will create model for books table.
php artisan make:migration create_books_table
Open file database -> migrations -> 2023_07_11_141714_create_books_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('book', function (Blueprint $table) {
$table->id();
$table->string('author');
$table->json('genre')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
};
Then we can run migration command to create table in database.
php artisan migrate
Now we will create Book.php model with two properties getter and setter. Let's run following command to create model:
php artisan make:model Book
Open file App -> Models -> Book.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
class Book extends Model
{
use HasFactory;
/**
* Write code on Method
*
* @return response()
*/
protected $fillable = [
'title', 'genre'
];
/**
* Get the user's first name.
*
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function genre(): Attribute
{
return Attribute::make(
get: fn ($value) => json_decode($value, true),
set: fn ($value) => json_encode($value),
);
}
}
Here we will create controller file BookController.php
file and implement code in index()
function. This function will create a record with sample data. Let's run below command to create controller file:
php artisan make:controller BookController
Open file App -> Http -> Controllers -> BookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Book;
class BookController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$sample = [
'author' => 'Robert T. Kiyosaki',
'genre' => [
'1' => 'Finance',
'2' => 'Education',
'3' => 'Personal'
]
];
$book= Book::create($sample);
dd($book->genre);
}
}
To connect controller file and the link that we access in browser bar. Let's insert a route in web.php:
Open file routes -> web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
/*
|--------------------------------------------------------------------------
| 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('book', [BookController::class, 'index']);
Finally, run server development to start server project by following command
php artisan serve
Open URL http://localhost:8000/ you will see the output as below
array:3 [
'1' => 'Finance',
'2' => 'Education',
'3' => 'Personal'
]
Hope it would help you, please have a nice day...
You might also like...
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him