PHP code example of sereny / postgrest

1. Go to this page and download the library: Download sereny/postgrest library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sereny / postgrest example snippets


User::where('age', '>', 18)->orderBy('name')->limit(10)->get();
// GET /users?age=gt.18&order=name.asc&limit=10

'connections' => [

    // ...

    'postgrest' => [
        'driver' => 'postgrest',
        'url' => env('PGREST_BASE_URI', 'http://localhost:3000'),
        'schema' => env('PGREST_SCHEMA', 'public'),
        'prefix' => env('PGREST_PREFIX', ''),
        'token' => env('PGREST_AUTH_TOKEN'),
        'headers' => [],
    ],
],

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'users';
}

// Create
$user = User::create(['name' => 'John', 'age' => 30]);

// Read
$user = User::find(1);
$users = User::where('age', '>=', 18)->orderBy('name')->limit(10)->get();

// Update
$user->update(['age' => 31]);

// Delete
$user->delete();

// Count & paginate
User::where('active', true)->count();
User::where('active', true)->paginate(15);

DB::connection('postgrest')
    ->table('users')
    ->whereIn('role', ['admin', 'editor'])
    ->get();

DB::connection('postgrest')->rpc('total_sales', ['year' => 2024]);

use Sereny\PostgREST\Eloquent\Model;

class User extends Model
{
    protected $connection = 'postgrest';

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
    }
}

$roles = User::find(1)->roles;                 // lazy
User::with('roles')->get();                     // eager, one embedded request
$roles = User::find(1)->roles()->withPivot('active')->get();

$user->roles()->attach($roleId);               // writes to the pivot table
$user->roles()->detach($roleId);

use Sereny\PostgREST\Eloquent\Model;

class Country extends Model
{
    protected $connection = 'postgrest';

    public function posts()
    {
        return $this->hasManyThrough(Post::class, User::class);
    }
}

Country::find(1)->posts;              // GET /countries?select=*,users(country_id,posts(*))
Country::with('posts')->get();        // eager, one nested embedded request
bash
php artisan vendor:publish --tag=postgrest-config