PostgreSQL JSONB in Laravel: Indexing &amp; Casting | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com) [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles  ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://msaied.com) [ Projects ](https://msaied.com/projects) [ Articles ](https://msaied.com/articles) [ Certificates ](https://msaied.com/certificates) [ Contact ](https://msaied.com#contact-section) 

  [ home ](https://msaied.com)    [ articles ](https://msaied.com/articles)    PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Bloat        On this page       1. [  PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Bloat ](#postgresql-jsonb-in-laravel-indexing-querying-and-casting-without-the-bloat)
2. [  When JSONB Makes Sense ](#when-jsonb-makes-sense)
3. [  Migration: Column + GIN Index ](#migration-column-gin-index)
4. [  Querying JSONB with Eloquent ](#querying-jsonb-with-eloquent)
5. [  Typed Casts: Stop Reading Raw Arrays ](#typed-casts-stop-reading-raw-arrays)
6. [  Updating Partial Paths ](#updating-partial-paths)
7. [  Takeaways ](#takeaways)

  ![PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Bloat](https://cdn.msaied.com/529/5d6560d5f6f0a2cdc483fbfecc24707d.png)

  #laravel   #postgresql   #eloquent   #jsonb   #performance  

 PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Bloat 
================================================================================

     9 Aug 2026      4 min read    ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said  

       Table of contents

1. [  01   PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Bloat  ](#postgresql-jsonb-in-laravel-indexing-querying-and-casting-without-the-bloat)
2. [  02   When JSONB Makes Sense  ](#when-jsonb-makes-sense)
3. [  03   Migration: Column + GIN Index  ](#migration-column-gin-index)
4. [  04   Querying JSONB with Eloquent  ](#querying-jsonb-with-eloquent)
5. [  05   Typed Casts: Stop Reading Raw Arrays  ](#typed-casts-stop-reading-raw-arrays)
6. [  06   Updating Partial Paths  ](#updating-partial-paths)
7. [  07   Takeaways  ](#takeaways)

 PostgreSQL JSONB in Laravel: Indexing, Querying, and Casting Without the Bloat
------------------------------------------------------------------------------

JSONB is one of PostgreSQL's most practical features for product engineers. It lets you store semi-structured data alongside relational columns without spinning up a separate document store. But used carelessly, JSONB columns become black holes: unindexed, untyped, and impossible to query efficiently.

This article covers the three things you actually need to get right: **indexing**, **querying via Eloquent**, and **casting to typed PHP objects**.

---

### When JSONB Makes Sense

JSONB is not a replacement for normalized tables. Use it when:

- The shape of the data varies per row (e.g., feature flags, metadata bags, third-party webhook payloads).
- You need to query *into* the structure, not just store and retrieve it.
- The alternative is an EAV table, which is almost always worse.

Avoid JSONB for data you join on, aggregate with `GROUP BY`, or reference from foreign keys.

---

### Migration: Column + GIN Index

```php
Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->jsonb('attributes')->default('{}');
    $table->timestamps();
});

// Separate migration for the index
DB::statement(
    "CREATE INDEX products_attributes_gin ON products USING GIN (attributes)"
);

```

The GIN (Generalized Inverted Index) index supports the `@>` containment operator, which powers `whereJsonContains`. Without it, every JSONB query does a full sequential scan.

If you only ever query a single key path, a partial B-tree index on an expression is cheaper:

```sql
CREATE INDEX products_attributes_color
    ON products ((attributes->>'color'));

```

---

### Querying JSONB with Eloquent

Laravel's query builder has first-class JSONB support through a handful of methods:

```php
// Containment: uses the GIN index via @>
Product::whereJsonContains('attributes->tags', 'sale')->get();

// Key existence (also GIN-indexed with jsonb_ops)
Product::whereRaw("attributes \?| array['color','size']");

// Scalar comparison on a path
Product::where('attributes->stock', '>', 0)->get();

// Nested path
Product::whereJsonContains('attributes->shipping->methods', 'express')->get();

```

`whereJsonContains` compiles to `@>` under the hood when targeting PostgreSQL, so your GIN index is used automatically. The scalar comparison (`attributes->stock`) casts to text by default — use `->>'stock'` for text or `(attributes->>'stock')::int` for numeric comparisons via `whereRaw`.

---

### Typed Casts: Stop Reading Raw Arrays

Returning a raw `array` from a JSONB column is a footgun. Define a typed cast instead:

```php
// app/Casts/ProductAttributes.php
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class ProductAttributes implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes): Attributes
    {
        return Attributes::fromArray(json_decode($value, true) ?? []);
    }

    public function set($model, string $key, $value, array $attributes): string
    {
        return json_encode($value instanceof Attributes ? $value->toArray() : $value);
    }
}

```

```php
// app/Data/Attributes.php
readonly class Attributes
{
    public function __construct(
        public readonly array $tags = [],
        public readonly ?string $color = null,
        public readonly int $stock = 0,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            tags: $data['tags'] ?? [],
            color: $data['color'] ?? null,
            stock: $data['stock'] ?? 0,
        );
    }

    public function toArray(): array
    {
        return ['tags' => $this->tags, 'color' => $this->color, 'stock' => $this->stock];
    }
}

```

```php
// Product model
protected $casts = [
    'attributes' => ProductAttributes::class,
];

```

Now `$product->attributes->color` is typed, IDE-friendly, and never returns `null` unexpectedly.

---

### Updating Partial Paths

Avoid re-serializing the entire column when you only change one key. Use `jsonb_set`:

```php
DB::table('products')
    ->where('id', $product->id)
    ->update([
        'attributes' => DB::raw(
            "jsonb_set(attributes, '{stock}', '" . (int) $newStock . "')"
        ),
    ]);

```

This is a single atomic write and avoids a read-modify-write race condition.

---

### Takeaways

- Always add a GIN index on JSONB columns you query with `whereJsonContains` or `@>`.
- Use expression indexes (B-tree on a path) when querying a single scalar key repeatedly.
- Wrap JSONB columns in a typed `CastsAttributes` class — raw arrays are untyped debt.
- Use `jsonb_set` for partial updates to avoid overwriting concurrent changes.
- JSONB is a tool for flexible metadata, not a substitute for relational modeling.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fpostgresql-jsonb-in-laravel-indexing-querying-and-casting-without-the-bloat-2&text=PostgreSQL+JSONB+in+Laravel%3A+Indexing%2C+Querying%2C+and+Casting+Without+the+Bloat) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fmsaied.com%2Farticles%2Fpostgresql-jsonb-in-laravel-indexing-querying-and-casting-without-the-bloat-2) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  Does whereJsonContains use a GIN index automatically in PostgreSQL?        Yes. Laravel compiles whereJsonContains to the @&gt; containment operator on PostgreSQL, which is supported by a GIN index created with the default jsonb_ops operator class. Without the index, the query falls back to a sequential scan. 

      Q02  Should I use json or jsonb in PostgreSQL with Laravel?        Always prefer jsonb. It stores data in a decomposed binary format, supports indexing, and allows operators like @&gt; and ?. The json type stores raw text and cannot be indexed efficiently. The storage overhead of jsonb is negligible in practice. 

      Q03  Can I use Spatie Laravel Data instead of a manual cast class?        Yes. Spatie Laravel Data DTOs implement CastsAttributes automatically when you cast a column to a Data class. This is a clean alternative if you already have the package in your project, and it adds validation on top of casting. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://msaied.com/articles) 

 [ ![Cursor Pagination and Lazy Collections at Scale in Laravel](https://cdn.msaied.com/536/3aab48ef4a4eaa26a3267637dc2ec8c7.png) laravel eloquent performance 

### Cursor Pagination and Lazy Collections at Scale in Laravel

Offset pagination breaks under large datasets. Learn how Laravel's cursor pagination and lazy collections let...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 11 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/cursor-pagination-and-lazy-collections-at-scale-in-laravel) [ ![Livewire v3.8.4 Released: Octane Memory Leak Fix and Fetch Redirect Handling](https://cdn.msaied.com/534/fdb2d91db2cb26fba0788d205b663031.png) livewire laravel octane 

### Livewire v3.8.4 Released: Octane Memory Leak Fix and Fetch Redirect Handling

Livewire v3.8.4 ships two important backports: a fix for a computed property listener memory leak under Larave...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 10 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/livewire-v384-released-octane-memory-leak-fix-and-fetch-redirect-handling) [ ![Laravel artisan dev: Run Server, Queue, Logs, and Vite in One Command](https://cdn.msaied.com/533/88ab98460b08aed42d6688eaa02a9620.png) Laravel Artisan Laravel 13 

### Laravel artisan dev: Run Server, Queue, Logs, and Vite in One Command

Laravel 13.16 introduced a first-party `php artisan dev` command that replaces the old Composer script, runnin...

  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MJ.jpg)  Mohamed Said 

 10 Aug 2026     3 min read  

  Read    

 ](https://msaied.com/articles/laravel-artisan-dev-run-server-queue-logs-and-vite-in-one-command) 

   [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://msaied.com)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

Explore

- [Home](https://msaied.com)
- [Projects](https://msaied.com/projects)
- [Articles](https://msaied.com/articles)
- [Certificates](https://msaied.com/certificates)
- [Contact](https://msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
