Saving JSON Objects in Laravel 5

Now, a couple of days ago, I started struggling my way through getting up and running with Laravel 5. If you’ve seen many of my articles, you’ll realize how Django-ish and Ionized some of them are.

PHP wasn’t my thing until I had to come up to speed with one of the world’s most used programming languages via the form of Laravel – a popular PHP Web application framework.

Why PHP? For a job application review process, but I guess if not for the job application, I would have missed out on this awesome framework. Gradually liking this tool more and more!

Lemme share my experience using Laravel with you later in a separate article. For now, let’s talk about how to save a JSON Object in Laravel. Very quickly!

The Model

Let’s say you’re building an app, a hypothetical one, where you’ll wanna nest multiple form inputs into a single field. That’s the preamble. So let us unwind the process gradually.

...
class Mymodel extends Model
{
  protected $casts = [
      'the_field' => 'array',
  ];
  protected $fillable = ['title', 'the_field'];
  protected $table = 'mymodel';
}
....

Only the first bullet in the list below is tightly related to our JSON-object-saving. So the above, in English:

With the above out of the way, let us consider how our incoming data should be shaped:

{
    title: "Duh",
    the_field: [
        "foo and bar",
        "entered a bar"
    ]
}

Then we have to chew on the incoming data in our controller and pass it on to the model for absorption.

Controller

We do so in our controller like this:

class QuestionsController extends Controller
{
    public function store(Request $request, Mymodel $mymodel) {
      $mymodel->create([
        'title'=>$request->title,
        // this or the one below will work.
        // 'option_name'=> $request->option_name,
        'option_name'=>Input::get('option_name'),
        ]);
      return back();
    }
}

… After were directed from our Routes which look like this:

Route::post('/create', 'MymodelController@create');

Controller

If you don’t wanna bother yourself trying to retrieve the data into your templates yet, you could simple check from your DB if the data was committed in the formatted way you expected, like so:

$ php artisan tinker

>>> DB::table('mymodel')->get()
// This should list all items you've added in DB including the ones with JSON Array objects

This has been a quick one.

I’ll be sharing a complete tutorial on my experience so far in building a simple Survey App in Laravel with y’all before the end of next week.

Exit mobile version