independent full stack developer

/ Developer's blog

How to use JSON and Laravel with MySQL

Wednesday, February 08, 2023

My lead framework is Laravel, and I really like to use it with MongoDB, and I do it for the most of time. But sometimes, especially when you worked with legacy code, I have to use MySQL that doesn't support JSON as datatype, so in this case I should use json_encode() everytime when I need to store Arrays and json_decode() when I need to get it back.

Laravel is a powerfull framework with a lot of small features for web artisans that makes our life easier, I want tell about Eloquent mutators and Array & JSON Casting.

How to use this mutator? It' easy, Laravel will do it automatically. Let's imaging that we have a some class for Event where we store Speakers, and need to store them in MySQL without JSON support. We can make something like this:


    /*
     * Get speakers array
     */
    public function getSpeakers()
    {

        $json = json_decode($this->speakers);

        if (!is_array($json)) {
            $json = [];
        }

        return $json;

    }

As we can see, we should use this method for json/array decoding, and the same way to save it. Let's try to use Laravel Json/Array casting, and make the class as next:

class Event extends Model
{

    protected $table = 'user_events';

 protected $casts = [
        'speakers' => 'array',
    ];

}

 

I added a special mutator array for speakers, and form this time I can use simple $event->speakers call, and everything will work. Laravel will convert array to json string and vice versa automatically. Magic.

Let's discover official documentation on Laravel website

1990 people already saw it