Working with array data type in Laravel
by durlavk
There is a list of things to learn and write. Hold on there is an array of things 😉ℹ️.
People love to work with array data types mostly due to it’s simplicity and ability store multiple data of same type in one variable. Let’s take a look at how array data type can be used to store data in a laravel application.
Laravel doesn’t have array as available column types. In order to store array data we have to make use of json column type and laravel casts functionality. Here is a step wise implementation of that.
- Step 0-
Create a new laravel project.
laravel new laradiy /* or */ composer create-project laravel/laravel laradiy - Step 1-
Create
ArrayDatamodel.cd laradiy php artisan make:model ArrayData -mc-mc will create migrations and controller for us.
- Step 2-
Edit migration table to accept array.
/database/migrations/2021_03_20_120154_create_array_data_table.phppublic function up() { Schema::create('array_data', function (Blueprint $table) { $table->id(); $table->json('random_list'); $table->timestamps(); }); }It will create a json column of
random_list, data will be stored as serialized JSON. - Step 3-
Modify the
ArrayDatamodel to acceptrandom_listand cast it as array./app/Models/ArrayData.phpclass Organisation extends Model { use HasFactory; protected $fillable= ['random_list']; protected $casts = [ 'random_list' => 'array' ]; }The array cast will automatically deserialize
random_listto a PHP array when you access it on your Eloquent model. - Step 4-
Now let’s modify the
ArrayDataControllerto store and display the data stored./app/Http/Controllers/ArrayDataController.phpuse App\Models\ArrayData; class ArrayDataController extends Controller { public function create() { ArrayData::create([ 'random_list' => [1,2,3], ]); return 'done'; } public function index() { $data = ArrayData::find(1); dd($data->random_list); } }The
createfunction will create and storerandom_listto your database. The index function will displayrandom_listarray. - Step 5-
Let’s create the routes to check our application.
/routes/web.phpuse App\Http\Controllers\ArrayDataController; Route::get('/arraydata', [ArrayDataController::class, 'index']); Route::get('/createdata', [ArrayDataController::class, 'create']); - Step 6-
Now lets run the migrations
php artisan migrate php artisan serve
Open localhost:8000 . Go to/createarray, it will create an entry in the database. Now go to/arraydata, and you will see yourrandom_listarray printed out.So, that’s how array data can be used in laravel. Hope this helps. See you later, alligator.