2 years ago

Working with Postgres JSONB in Laravel 5.5

Posted 2 years ago by phpguru

Here's our table schema

    Schema::create('contacts', function(Blueprint $table)
        $table->uuid('id')->default(\DB::raw('gen_random_uuid()'))->comment('primary key');
        $table->string('email', 100)->nullable()->comment('email address');
        $table->jsonb('data')->nullable()->comment('Any params go here');

Here's an insert statement in Tinker

Contact::create(['email'=>'[email protected]', 'data'=>'{"first_name":"Geoff","info":{"id":1234123,"groups":[101,202,303]}}'])

Here's a sample query

Contact::where('data->first_name', 'Geoff')->first()
App\Models\Contact {#890
   id: "8eeab075-57ae-4b29-8aca-df8f7c296dd4",
   email: "[email protected]",
   data: "{"first_name": "Geoff", "info": {"id": 1234123, "groups": [101, 202, 303]}}",
   created_at: "2018-01-25 18:04:03",
   updated_at: "2018-01-25 18:04:03",

So far so good.

How do I find contacts that belong to group 202?

Please sign in or create an account to participate in this conversation.