How to Store Data Array in Database on Laravel 9?
<?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),
);
}
}
<?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']);
<?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);
}
}
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/item
You can see database output and print variable output:
Database Output:
array:3 [
1 => "One"
2 => "Two"
3 => "Three"
]