Storing an array in a Database by using Laravel is a bit tricky. When we fall into a situation where we need to handle a field that will get random data attributes, we need to use some tricks. Here you will learn how to store array values in a database using Laravel. Nothing is rocket science. Rather than all tricks long, you will see some simple functions.
Storing array value in the database using Laravel
Suppose you have
a JSON Object like this -
{
"data":[{"id":1,
"level":"School",
"organizationName":"MDpur school",
"subject":"arts",
"yearStart":"2001",
"yearEnd":"2008"
},
{"id":2,
"level":"CLG",
"organizationName":"MDpur CLG",
"subject":"science k",
"yearStart":"2009",
"yearEnd":"2012"
}
]
}
Now we are going to store this on the La ravel database. Here
I like to share some easy steps that will make your sense more straightforward.
Keep following this.
Step 1: We need to ensure that the database field is
nonexistent from the beginning. Let us make a Laravel post route.
Route::post('getObject',[TestController::class,' getObject ']);
Step 2: Now make a controller name TextController, and there
will be a method getObject.
public function getObject(Request $request){ UserProfile::where('id',1)->update(['education'=>json_encode($request->data)]); return 1; }
This getObject method will get the JSON from the API endpoint
and store it on the database UserProfile table in the education field.
How to get back the JSON data from Laravel database
If you want to return the JSON data, let me show you two
more simple steps. Those are also easy. You can get it quickly.
Step 1: Make a simple get route on the web.php or any web
page and mention your desired controller and methods.
Route::get('test4',[TestController::class,'showObject']);
Step 2: Now, you need to get the database. Before returning
it decode it. After checking this API end, you will have a JSON object you put
on the database a few moments ago.
public function showObject(){ $data = UserProfile::where('id',1)->get('education')->first(); return json_decode(json_decode($data)->education); }
Seeing all the things are such easy. We appreciate people asking
us if they have any queries. Even if you want to sponsor us, please email us
from the email section.