laravel json eloquent

Laravel JSON Eloquent

As a programmer, I have been working with Laravel for quite some time now. Laravel is a powerful and popular PHP framework used for web development. One of the features that make Laravel stand out is its Eloquent ORM (Object-Relational Mapping) which makes working with databases a breeze.

JSON (JavaScript Object Notation) is a lightweight data format that is easy to read and write. Laravel's Eloquent ORM provides a convenient way to work with JSON data in your database tables.

Storing JSON Data using Eloquent

Storing JSON data in Laravel's Eloquent ORM is quite simple. You can store JSON data in a column using the json type provided by Laravel's migration schema builder.

        Schema::create('users', function (Blueprint $table) {
            $table->json('metadata'); //Store JSON data in metadata column

Once you have created your table, you can easily add JSON data to it using the Eloquent ORM:

        $user = new User;
        $user->name = 'John Doe';
        $user->metadata = json_encode(['age' => 25, 'address' => '123 Main St.']);

You can also retrieve JSON data from the table using Eloquent:

        $user = User::find(1);
        $metadata = json_decode($user->metadata);

Querying JSON Data using Eloquent

Eloquent provides a powerful way to query JSON data stored in your database tables. You can use the whereJsonContains method to query JSON data in Laravel:

        $users = User::whereJsonContains('metadata->address', 'Main St.')->get();

The above code will retrieve all users whose address contains 'Main St.' in their metadata column.


Laravel's Eloquent ORM makes working with JSON data in your database tables a simple and convenient process. You can easily store, retrieve, and query JSON data using the Eloquent ORM's methods. If you are working with JSON data in Laravel, make sure to take advantage of Eloquent's powerful features.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]