A tutorial on how to store arrays to SQL databases using JSON and CASTS in Laravel

Anselm Mba
Level Up Coding
Published in
3 min readApr 11, 2020

--

In this article, we look at how to store arrays in a Laravel or Lumen Application using json datatype and cast property.

This is an offshoot of my previous article “An awesome way to store arrays to SQL database in PHP”. Check it out for a full overview of how arrays can be stored and retrieved from sql databases.

STEP 1

In our Laravel Application, we will make our model and migration from the terminal

— > make a contents_arr model and migration in your terminal

php artisan make:model ContentsArr -m

STEP 2

We edit our migration file and set our array columns as json

— > edit the migration (create_contents_arrs_table) as follows:

<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;class CreateContentsArrsTable extends Migration{/*** Run the migrations.** @return void*/public function up(){Schema::create('contents_arrs', function (Blueprint $table) {$table->increments('id');$table->json('arr_text1');$table->json('arr_text2');$table->timestamps();});}/*** Reverse the migrations.** @return void*/public function down(){Schema::dropIfExists('contents_arrs');}}

STEP 3

Let's also edit our model class and use Laravel’s awesome $cast property to return array values from the database. Also, we make our ‘arr_text1’ and ‘arr_text2’ columns mass assignable.

— > edit the model (ContentsArr) as follows

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class ContentsArr extends Model{protected $fillable = ['arr_text1', 'arr_text2'];//Tell laravel to fetch text values and set them as arraysprotected $casts = ['arr_text1' => 'array','arr_text2' => 'array'];}

STEP 4

It’s now time to make a controller that will pass our data to the database.

— > make a ContentsArrController in the terminal

php artisan make:controller ContentsArrController

STEP 5

Here we create the array data we want to pass to Eloquent for storage into the database and return a success response of the contents_arr record if the arrays are stored successfully or an error response if not successful

— > edit controller (ContentsArrController) as follows

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class ContentsArrController extends Controller{// Create a new contents_arr entry.public function createContents(){$contents_arr = \App\ContentsArr::create(['arr_text1' => ['Toni Abbah','Anastacia Mast','Soji Igbonna'],'arr_text2' => ['username'=>'torah','name'=>'Toni Abbah']]);if($contents_arr) {return response()->json(['status' => 'success','data' => $contents_arr]);}return response()->json(['status' => 'fail','message' => 'failed to create content_arr record']);}}

STEP 6

Finally, we route our application through a get request to the createContents method in our controller. This way we can simply test our implementation via a browser.

— > now let’s set up our route

<?php/*|--------------------------------------------------------------------------| 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('/contents-arr', 'ContentsArrController@createContents');

Here we go… in the browser we use the hit the endpoint: http://yourbaseurl/contents-arr

Results in pictures!

contents_arrs database table
browser response in json format

Suweeeet!!!

We have successfully implemented how you store and retrieve arrays using json and casts respectively!

I hope it was fun, simple and clear.

As always thanks for hanging!

--

--

Anselm is a naija focused software engineer with laravel and nodejs. Has passion for the web and programming. Enjoys crafting solutions and speaking code!