melanholly
melanholly

Reputation: 772

Search column of JSON data in PostgreSQL table

I need to store some JSON data in PostgreSQL table to use it as dynamic route generator. The migration is simple:

Schema::create($this->tablename, function (Blueprint $table)
{
    $table->increments('id');
    $table->string("uri", 123);
    $table->json("middleware")->nullable();
    $table->string("as", 123)->nullable();
}

I store the data this way:

$a = new Route();
$a->uri = "/test1";
$a->middleware=json_encode(["auth","web"]);
$a->as = "TestController@test";
$a->save();

So let's say that I need to filter all the routes that have auth middleware. How can I do it?

When I try

Route::where('middleware', 'AS', 'auth')->get();

...I get an error. Is it possible to use it like that?

I use Laravel 5.2 and PostgreSQL 9.3.12.

Edit

If you are using PostgreSQL 9.4 or later and have Laravel framework with version bigger than 5.2.29 you can use this syntax:

Route::where('middleware','@>','"auth"')->get();

Upvotes: 0

Views: 137

Answers (1)

WhSol
WhSol

Reputation: 116

Change where to whereRaw and query for json field

Route::whereRaw("middleware->> 'auth'")->get(); 

Or

Route::whereRaw("middleware::json->> 'auth'")->get(); 

Upvotes: 1

Related Questions