Giter VIP home page Giter VIP logo

phpsupabase's Introduction

PHPSupabase

PHPSupabase is a library written in php language, which allows you to use the resources of a project created in Supabase (supabase.io), through integration with its Rest API.

Content

About Supabase

Supabase is "The Open Source Firebase Alternative". Through it, is possible to create a backend in less than 2 minutes. Start your project with a Postgres Database, Authentication, instant APIs, realtime subscriptions and Storage.

PHPSupabase Features

  • Create and manage users of a Supabase project
  • Manage user authentication (with email/password, magic links, among others)
  • Insert, Update, Delete and Fetch data in Postgres Database (by Supabase project Rest API)
  • A QueryBuilder class to filter project data in uncomplicated way

Instalation & loading

PHPSupabase is available on Packagist, and instalation via Composer is the recommended way to install it. Add the follow line to your composer.json file:

"rafaelwendel/phpsupabase" : "^0.0.1"

or run

composer require rafaelwendel/phpsupabase

How to use

To use the PHPSupabse library you must have an account and a project created in the Supabase panel. In the project settings (API section), you should note down your project's API key and URL. (NOTE: Basically we have 2 suffixes to use with the url: /rest/v1 & /auth/v1, but since version 0.0.5 the definition of one of these suffixes is optional)

To start, let's instantiate the Service() class. We must pass the API key and url in the constructor

<?php

require "vendor/autoload.php";

$service = new PHPSupabase\Service(
    "YOUR_API_KEY", 
    "https://aaabbbccc.supabase.co"
);

//In versions 0.0.4 or earlier it is necessary to set the suffix
$service = new PHPSupabase\Service(
    "YOUR_API_KEY", 
    "https://aaabbbccc.supabase.co/auth/v1" // or https://aaabbbccc.supabase.co/rest/v1
);

The Service class abstracts the actions with the project's API and also provides the instances of the other classes (Auth, Database and QueryBuilder).

Auth class

Let's instantiate an object of the Auth class

$auth = $service->createAuth();

The $auth object has several methods for managing project users. Through it, it is possible, for example, to create new users or even validate the sign in of an existing user.

Create a new user with email and password

See how to create a new user with email and password.

$auth = $service->createAuth();

try{
    $auth->createUserWithEmailAndPassword('[email protected]', 'NewUserPassword');
    $data = $auth->data(); // get the returned data generated by request
    echo 'User has been created! A confirmation link has been sent to the '. $data->email;
}
catch(Exception $e){
    echo $auth->getError();
}

This newly created user is now in the project's user table and can be seen in the "Authentication" section of the Supabase panel. To be enabled, the user must access the confirmation link sent to the email.

In the third parameter of the createUserWithEmailAndPassword method you can pass an array containing the user_metadata to be saved (Ex: name and age)

$user_metadata = [
    'name' => 'Lebron James',
    'age' => '34'
];
$auth->createUserWithEmailAndPassword('[email protected]', 'LebronPassword', $user_metadata);

Sign in with email and password

Now let's see how to authenticate a user. The Authentication request returns a access_token (Bearer Token) that can be used later for other actions and also checks expiration time. In addition, other information such as refresh_token and user data are also returned. Invalid login credentials result in throwing a new exception

$auth = $service->createAuth();

try{
    $auth->signInWithEmailAndPassword('[email protected]', 'UserPassword');
    $data = $auth->data(); // get the returned data generated by request

    if(isset($data->access_token)){
        $userData = $data->user; //get the user data
        echo 'Login successfully for user ' . $userData->email;

        //save the $data->access_token in Session, Cookie or other for future requests.
    }
}
catch(Exception $e){
    echo $auth->getError();
}

Get the data of the logged in user

To get the user data, you need to have the access_token (Bearer Token), which was returned in the login action.

$auth = $service->createAuth();
$bearerToken = 'THE_ACCESS_TOKEN';

try{
    $data = $auth->getUser($bearerToken);
    print_r($data); // show all user data returned
}
catch(Exception $e){
    echo $auth->getError();
}

Update user data

It is possible to update user data (such as email and password) and also create/update metadata, which are additional data that we can create (such as first_name, last_name, instagram_account or any other).

The updateUser method must take the bearerToken as argument. In addition to it, we have three more optional parameters, which are: email, password and data (array). If you don't want to change some of this data, just set it to null.

An example of how to save/update two new meta data (first_name and last_name) for the user.

$auth = $service->createAuth();
$bearerToken = 'THE_ACCESS_TOKEN';

$newUserMetaData = [
    'first_name' => 'Michael',
    'last_name'  => 'Jordan'
];

try{
    //the parameters 2 (email) and 3(password) are null because this data will not be changed
    $data = $auth->updateUser($bearerToken, null, null, $newUserMetaData);
    print_r($data); // show all user data returned
}
catch(Exception $e){
    echo $auth->getError();
}

Note that in the array returned now, the keys first_name and last_name were added to user_metadata.

Database class

The Database class provides features to perform actions (insert, update, delete and fetch) on the Postgre database tables provided by the Supabase project.

For the samples below, consider the following database structure:

categories (id INT AUTO_INCREMENT, categoryname VARCHAR(32))
products (id INT AUTO_INCREMENT, productname VARCHAR(32), price FLOAT, categoryid INT)

The Database class is also instantiated from the service object. You must pass the table that will be used and its respective primary key (usually id).

Let's create an object to work with the categories table:

$db = $service->initializeDatabase('categories', 'id');

Through the db variable it is possible to perform the actions on the categories table.

NOTE: If Row Level Security (RLS) is enabled in the used table, pass the bearerToken to the Service object:

$bearerToken = 'THE_ACCESS_TOKEN'; //returned in the login action.
$db = $service->setBearerToken($bearerToken)->initializeDatabase('categories', 'id');

Insert data

Inserting a new record in the categories table:

$db = $service->initializeDatabase('categories', 'id');

$newCategory = [
    'categoryname' => 'Video Games'
];

try{
    $data = $db->insert($newCategory);
    print_r($data); //returns an array with the new register data
    /*
        Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [categoryname] => Video Games
                )

        )
    */
}
catch(Exception $e){
    echo $e->getMessage();
}

Now let's insert a new product from category 1 - Video Games:

$db = $service->initializeDatabase('products', 'id');

$newProduct = [
    'productname' => 'XBOX Series S',
    'price'       => '299.99',
    'categoryid'  => '1' //Category "Video Games"
];

try{
    $data = $db->insert($newProduct);
    print_r($data); //returns an array with the new register data
    /*
        Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [productname] => XBOX Series S
                    [price] => 299.99
                    [categoryid] => 1
                )
        )
    */
}
catch(Exception $e){
    echo $e->getMessage();
}

Update data

To update a record in the database, we use the update method, passing as parameter the id (PK) of the record to be updated and an array containing the new data (NOTE: For now, it is not possible to perform an update using a parameter other than the primary key).

In the example below, we will update the productname and price of the product with id=1 ("Xbox Series S" to "XBOX Series S 512GB" and "299.99" to "319.99"):

$db = $service->initializeDatabase('products', 'id');

$updateProduct = [
    'productname' => 'XBOX Series S 512GB',
    'price'       => '319.99'
];

try{
    $data = $db->update('1', $updateProduct); //the first parameter ('1') is the product id
    print_r($data); //returns an array with the product data (updated)
    /*
        Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [productname] => XBOX Series S 512GB
                    [price] => 319.99
                    [categoryid] => 1
                )
        )
    */
}
catch(Exception $e){
    echo $e->getMessage();
}

Delete data

To delete a record from the table, just call the delete method and pass the id (PK) of the record to be deleted as a parameter.

The following code deletes the product of id=1 in the products table:

$db = $service->initializeDatabase('products', 'id');

try{
    $data = $db->delete('1'); //the parameter ('1') is the product id
    echo 'Product deleted successfully';
}
catch(Exception $e){
    echo $e->getMessage();
}

Fetch data

The following methods for fetching data are available in the Database class:

  • fetchAll(): fetch all table records;
  • findBy(string $column, string $value): fetch records filtereds by a column/value (using the = operator);
  • findByLike(string $column, string $value): fetch records filtereds by a column/value (using the LIKE operator);
  • join(string $foreignTable, string $foreignKey): make a join between the seted table and another table related and fetch records;
  • createCustomQuery(array $args): build a custom SQL query. The following keys are valid for the args argument:
    • select
    • from
    • join
    • where
    • limit
    • range

All the mentioned methods return the self instance of Database class. To access the fetched data, call the getResult method.

See some examples:

$db = $service->initializeDatabase('products', 'id');

try{
    $listProducts = $db->fetchAll()->getResult(); //fetch all products
    foreach ($listProducts as $product){
        echo $product->id . ' - ' . $product->productname . '($' . $product->price . ') <br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

Now, an example using the findBy method:

$db = $service->initializeDatabase('products', 'id');

try{
    $listProducts = $db->findBy('productname', 'PlayStation 5')->getResult(); //Searches for products that have the value "PlayStation 5" in the "productname" column
    foreach ($listProducts as $product){
        echo $product->id . ' - ' . $product->productname . '($' . $product->price . ') <br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

Searching for products and adding a join with the categories table:

$db = $service->initializeDatabase('products', 'id');

try{
    $listProducts = $db->join('categories', 'id')->getResult(); //fetch data from "products" JOIN "categories"
    foreach ($listProducts as $product){
        //SHOW "productname" - "categoryname"
        echo $product->productname . ' - ' . $product->categories->categoryname . '<br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

An example of a custom query to search id,productname,price for all products "JOIN" categories filtering by price (price greater than 200.00):

$db = $service->initializeDatabase('products', 'id');

$query = [
    'select' => 'id,productname,price',
    'from'   => 'products',
    'join'   => [
        [
            'table' => 'categories',
            'tablekey' => 'id'
        ]
    ],
    'where' => 
    [
        'price' => 'gt.200' //"gt" means "greater than" (>)
    ]
];

try{
    $listProducts = $db->createCustomQuery($query)->getResult();
    foreach ($listProducts as $product){
        echo $product->id . ' - ' . $product->productname . '($' . $product->price . ') <br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

Other examples for custom query:

//products with price > 200 AND productname LIKE '%n%'
$query = [
    'select' => 'id,productname,price',
    'from'   => 'products',
    'where' => 
    [
        'price' => 'gt.200', //"gt" means "greater than" (>)
        'productname' => 'like.%n%' //like operator
    ]
];

//products with categoryid = 1
$query = [
    'select' => 'id,productname,price',
    'from'   => 'products',
    'where' => 
    [
        'categoryid' => 'eq.1', //"eq" means "equal" (=)
    ]
];

//products with price < 1000 LIMIT 4 results
$query = [
    'select' => 'id,productname,price',
    'from'   => 'products',
    'where' => 
    [
        'price' => 'lt.1000', //"lt" means "less than" (<)
    ],
    'limit' => 4 //4 first rows
];

Comparison operators

The main operators available for the where clause:

  • eq: equal
  • neq: not equal
  • gt: greater than
  • gte: greater than or equal
  • lt: less than
  • lte: less than or equal
  • like: search for a specified pattern in a column
  • ilike: search for a specified pattern in a column (case insensitive)

Other operators available:

  • is
  • in
  • cs
  • cd
  • sl
  • sr
  • nxl
  • nxr
  • adj
  • ov
  • fts
  • plfts
  • phfts
  • wfts
  • not.eq
  • not.neq
  • not.gt
  • not.gte
  • not.lt
  • not.lte
  • not.like
  • not.ilike
  • not.is
  • not.in
  • not.cs
  • not.cd
  • not.sl
  • not.sr
  • not.nxl
  • not.nxr
  • not.adj
  • not.ov
  • not.fts
  • not.plfts
  • not.phfts
  • not.wfts

QueryBuilder class

The QueryBuilder class provides methods for dynamically building SQL queries. It is instantiated from the service object.

$query = $service->initializeQueryBuilder();

NOTE: If Row Level Security (RLS) is enabled on any of the tables used, pass the bearerToken to the Service object:

$bearerToken = 'THE_ACCESS_TOKEN'; //returned in the login action.
$query = $service->setBearerToken($bearerToken)->initializeQueryBuilder();

Available methods:

  • select(string $select): the fields (comma separated) or *
  • from(string $from): the table
  • join(string $table, string $tablekey, string $select = null): related table
  • where(string $column, string $value): conditions
  • limit(int $limit): limit rows
  • order(string $order): the "order by" field
  • range(string $range): results range (E.g. "0-3")

All the mentioned methods return the self instance of QueryBuilder class. To run the mounted query, call the execute method. Then, to access the fetched data, call the getResult method.

An example to fetch all data from the products table:

$query = $service->initializeQueryBuilder();

try{
    $listProducts = $query->select('*')
                ->from('products')
                ->execute()
                ->getResult();
    foreach ($listProducts as $product){
        echo $product->id . ' - ' . $product->productname . '($' . $product->price . ') <br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

An example to fetch all data from the products "JOIN" categories:

$query = $service->initializeQueryBuilder();

try{
    $listProducts = $query->select('*')
                ->from('products')
                ->join('categories', 'id')
                ->execute()
                ->getResult();
    foreach ($listProducts as $product){
        echo $product->id . ' - ' . $product->productname . '($' . $product->price . ') - '. $product->categories->categoryname .' <br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

Fetch products with categoryid=1 and price>200 order by price:

$query = $service->initializeQueryBuilder();

try{
    $listProducts = $query->select('*')
                ->from('products')
                ->join('categories', 'id')
                ->where('categoryid', 'eq.1') //eq -> equal
                ->where('price', 'gt.200') // gt -> greater than
                ->order('price.asc') //"price.desc" for descending
                ->execute()
                ->getResult();
    foreach ($listProducts as $product){
        echo $product->id . ' - ' . $product->productname . '($' . $product->price . ') - '. $product->categories->categoryname .' <br />';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

Some of the operators to be used in the where method can be seen in the Comparison operators section.

phpsupabase's People

Contributors

rafaelwendel avatar solarscreen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

phpsupabase's Issues

Sort Order

Ive used the QueryBuilder to order the results like so:

    $listProducts = $query->select('*')
                ->from('table')
                ->range('0-0')
                ->order('color')
                ->execute()
                ->getResult();

Which gives me the first result ordering by 'color' descending. How can I do the same thing but ascending?

Thanks!

Remove user

There is a getUser function, but no removeUser function.

I tried adding it myself by looking at their JS SDK but don't find the correct REST endpoint (tried /admin/user/[id] but that doesn't seem to work for me).

Any chance you can add it in?

Call to undefined method stdClass::update()

public function like_dogs(Request $request){
$service = new \PHPSupabase\Service(
"eyJhbGciwOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ewogICJyb2xlIjogImFub24iLAogICJpc3MiOiAicW3VwYWJhc2UiLAogICJApYXQiOiAxNjkxNzkxMjAwLAogICJleHAiOiAxODQ5NjQ0MDAwCn01.l9f3OhYMcvuuf14WKbF6zdSoNfP3TXz7yViMkNIgV0w",
"https://viz6101212.ru"
);
$db = $service->initializeDatabase('Posts', 'id');
$postId = $request->input('postId');
$post_sent = $db->findBy('id', $postId)->getResult();
$post_sent = $post_sent["0"];
$liked_ids = $post_sent->likedIDs;
$disliked_ids = $post_sent->dislikedIDs;
if (in_array(\Session::get('uid'), $disliked_ids)) {
$post_sent->update([

        ]);
        $post_sent->update([
            
        ]);
        return redirect()->back();
    }
    if (in_array(\Session::get('uid'), $liked_ids)) {
        $post_sent->update([
            
        ]);
        return redirect()->back();
    }
    else{
        $post_sent->update('likedIDs',\Session::get('uid'));
        return redirect()->back();
    }
}

Add support for return type 'minimal' on INSERT

Hello,

I came across one issue when trying to perform an INSERT on a table where the user only has INSERT priviledges enabled in RLS and not SELECT permission. The use case is for example an application where a user can provide anonymous feedback that gets added to the database, but is not allowed to view any submitted feedback.

Currently the library defaults to return type representation as it is hardcoded in the database class:

$this->service->setHeader('Prefer', 'return=representation');

To fix the issue about RLS blocking the INSERT due to the added SELECT query it needs to be changed to return=minimal if required which is currently not supported. My suggestion would be to default to return type representation in executeDml function but add the option to overwrite this by insert function if set by the user.

This issue was also once present in Supabase JS library, the discussion can be found here for reference: https://github.com/orgs/supabase/discussions/4107

Project References

Project References

Where did you get the references to make the classes and functions? From the official JS repository? supabase.js

Or did you do it with your own ideas?

You need to URLencode!

diff --git a/vendor/rafaelwendel/phpsupabase/src/QueryBuilder.php b/vendor/rafaelwendel/phpsupabase/src/QueryBuilder.php
index 681afff..32dfd92 100644
--- a/vendor/rafaelwendel/phpsupabase/src/QueryBuilder.php
+++ b/vendor/rafaelwendel/phpsupabase/src/QueryBuilder.php
@@ -113,7 +113,7 @@ class QueryBuilder {
*/
public function where(string $column, string $value) : QueryBuilder
{

  •    $this->query['where'][] = $column . '=' . $value;
    
  •    $this->query['where'][] = $column . '=' . urlencode($value);
       return $this;
    
    }

`404 Not Found` response: 404 page not found

Thank you for building this library!
When I try to use
$db = $service->initializeDatabase('categories', 'id');
$newCategory = ['categoryname' => '[email protected]'];
$data = $db->insert($newCategory);

I get the error
Client error: 'POST https://MY_URL_PROJECT.supabase.co/auth/v1/categories' resulted in a '404 Not Found' response: 404 page not found

Do you have any suggestion what might cause this?

createUserWithEmailAndPassword overwrites if exist

$auth = $service->createAuth();
This seems to be a bug but not sure if it is with this code or supabase. If this is called and the user exist, the password and any metadata passed is overwritten.

Possible security issue that someone could reset another user's password using just the signup form.

I am still developing and testing but I think an error should be returned if the email already exist.

Also, it says confirm email is sent but supabase seems to send if new and not already exist.

try{
$auth->createUserWithEmailAndPassword('[email protected]', 'bxxxy');
$data = $auth->data(); // get the returned data generated by request
echo 'User has been created! A confirmation link has been sent to the '. $data->email;
}
catch(Exception $e){
echo $auth->getError();
}

SignInWithOAuth function

Hi, is it possible to implement a sign in with oauth function (especially for google and discord) with this library?

Add limit in QueryBuilder please

Add limit in QueryBuilder please

  if(isset($this->query['limit'])){
        $queryString .= '&limit=' . $this->query['limit'];
    }

/**
 * Add the "limit" to the query
 * @access public
 * @param $range String The interval of fetch registers
 * @return QueryBuilder
 */
public function limit(string $range) : QueryBuilder
{
    $this->query['limit'] = $range;
    return $this;
}

Database.php in createCustomQuery()

    if(isset($args['limit'])){
        $queryBuilder->limit($args['limit']);
    }

Security issue

I didn't find any method to check input data like Prepared Statement against SQL injection attacks

Timestamp is not null

Is it possible using the QueryBuilder to query Timestamps for not null? I tried:

->where('DATE','is.not null')

and

->where('DATE','not.null')

500 error on ilike, like on some string

Hello, I am getting a 500 error from Supabase on like, ilike query on some string, example:
try{
$listClients = $query->select('')
->from('clients')
->where('department_name', 'ilike.%cal%')
->execute()
->getResult();
foreach ($listClients as $client){
$resp[] = $client;
}
}
Same call is working if I change 'cal' to 'matt':
try{
$listClients = $query->select('
')
->from('clients')
->where('department_name', 'ilike.%matt%')
->execute()
->getResult();
foreach ($listClients as $client){
$resp[] = $client;
}
}
I was able to make all string work adding urlencode at the ilike statement:
try{
$listClients = $query->select('*')
->from('clients')
->where('department_name', urlencode('ilike.%cal%'))
->execute()
->getResult();
foreach ($listClients as $client){
$resp[] = $client;
}
}
Is this a normal behaviour?
I don't see in the documentation that urlencode must be used in the where statement using like.
Thank you!

Documentation "bug": Optional parameters + type order

I got warnings in my code base when using library functions with optional parameters, when using e.g. initializeDatabase.

Argument '2' passed to initializeDatabase() is expected to be of type PHPSupabase\optional, string given PHP(PHP0406)

https://github.com/rafaelwendel/phpsupabase/blob/main/src/Service.php#L160

Documentation : https://docs.phpdoc.org/3.0/guide/references/phpdoc/tags/param.html

In my case (VSCODE + DEVSENSE PHP extension) I got errors, as it parses the first word after the variable as the type. Which is Optional int this case.

And as I see now, the documented way of PHPDoc is even:

@param [<Type>] [name] [<description>]

And in this lib,

@param [name] [] [(optional)] []

is used mostly...

With also String needs to be a lower case string.

Or do you use another method/library for documentation?

Thanks!

documentation spelling mistake

i'm not into git so i can't open a pull request atm.
but in the documentation at "Sign in with email and password"
theres "acess_token" instead of "access_token" 2 times.
it's just a spelling mistake but the example code doesnt work.

it would be really nice for the next person if someone could fix that.
thanks!

Signup & recover password without redirectUrl

Hi, from the official docs both the signup & recover method include the emailRedirectTo param in "options" which to specific the request redirection. Is this emailRedirectTo will be add on into these method?

I need create two supabase services, for auth and other for consume?

define('SUPABASE_URL', 'https://id-project.supabase.co/');
define('SUPABASE_KEY', 'apikeysupabase...');

$serviceAuth = new PHPSupabase\Service(
    SUPABASE_KEY, 
    SUPABASE_URL . 'auth/v1/'
);

$auth = $serviceAuth->createAuth();

try{
    $auth->signInWithEmailAndPassword('[email protected]', '1234');
    $data = $auth->data(); // get the returned data generated by request

    if(isset($data->access_token)){
        $userData = $data->user; //get the user data
        echo 'Login successfully for user ' . $userData->email;

        //save the $data->access_token in Session, Cookie or other for future requests.
    }
}
catch(Exception $e){
    print_r($e);
}

If the url route is set with supabase/auth/v1 then the queries cannot be performed.
I nedd create another service with resource consumption url with supabase.co/rest/v1

$service = new PHPSupabase\Service(
    SUPABASE_KEY, 
    SUPABASE_URL . 'rest/v1/'
);

$db = $service->initializeDatabase('lightprice', 'id');

Or is it working correctly as it should be used?

captcha verification process failed

When I enable "Bot and Abuse Protection" using the service_role key it says "Server error: POST https://sdqczznijvha.supabase.co/auth/v1/signup resulted in a 500 Internal Server Error response : {"code":500,"msg":"captcha verification process failed","error_id":"8611cf16c0276459-SJC"} "

When I also use this service_role key from javascript I am able to skip verification.

I'm using version 0.0.7.

signInWithRefreshToken doesn't work.

edit: i made sure the refresh token is not used anywhere else and this also happens with new refresh tokens created one second before running this code and receiving the error.

I have signed in before this codes runs and saved the session in my cookies.
After 1 hour it runs the following code.
Result is either null or this:

image

This is the code for refreshing:

image

Count total rows?

How can I get the total rows count of a table ?

Or a better question is how can I get the headers from a response?
I added in the service class $header : count => 'exact', but now I need to access the header response.

Thank you

Where 2 conditions for a field (e.g. date)

I am trying to make a query and get the data based on created_at field for a specific date interval.

How can I add to conditions for one field?

Currently I have this;

    $query = [
      'select' => 'created_at',
      'from'   => 'usersData',
      'where' =>
      [
        'created_at' => 'gte.' . $this->start_date . 'T00:00:00',
      ],

But I want to add this as well:

'created_at' => 'lt.' . $this->end_date . 'T23:59:59',

Thanks!

Count records on table

I tried

$query = $service->initializeQueryBuilder();

try{
    $listProducts = $query->select('COUNT(*)')
                ->from('messages')
                ->execute()
                ->getResult();
    var_dump($listProducts);
}
catch(Exception $e){
    echo $e->getMessage();
}

Result

Client error: `GET https://***.supabase.co/rest/v1/messages?select=COUNT(*)` resulted in a `400 Bad Request` response:
{"code":"PGRST200","details":"Searched for a foreign key relationship between 'messages' and 'COUNT' in the schema 'publ (truncated...)

Add support for RCP

Hi @rafaelwendel

I am using your library in a project where I need to run some advanced queries containing aggregates etc. The createCustomQuery function does not cover this (neither does the equivalent in Supabase itself).

To get around that, I am creating database functions via the Supabase UI and using their RPC API endpoint to execute the function and return the results. This works well!

RPC is not part of your library so I am manuallyu calling it this way:

$service = self::get_service( 'rest' );
$result = $service->executeHttpRequest( 'GET', $my_base_url . 'rpc/function_name', [ 'headers' => $service->getHeaders() ] );

This works without issue, but it would be cleaner if your library had a function to call RPC directly. Perhaps you can consider to include it in a next update? Thanks!

no Route matched with those values

Thank you for building this library!

When I try to use $auth->signInWithEmailAndPassword I get the error no Route matched with those values .

Do you have any suggestion what might cause this?

JWT Expired

How to solve the following error:

**error: `POST https://xxx.supabase.co/rest/v1/yyy` resulted in a `401 Unauthorized` response:
{"code":"PGRST301","details":null,"hint":null,"message":"JWT expired"}**

Q: How to retrieve callback fragment parameters from frontend after login?

This is offtopic. I was just curious about people who are using supabase for their PHP projects, how do you authenticate your users when the async login didn't return anything useful? Do you parse the url fragment returned on the callback url and make a hidden form on the page to initiate a POST request to server so that PHP able to get the values?
I'm implementing Magic Link auth on my Laravel project, and I was brain f*ed thinking how to pass those values to the backend because the values are placed in fragments. So I came across this but found out it is also using the API endpoints only and nothing special, all the auth login function return void. So it should be similar results to my current implementation using supabase JS.
Sorry for my noob question... I'm not an expert, I hope to get more information about this, since there's not much information about this on the internet. Thanks!

$auth->getUser(); error

Hi,
when I try to use the following:

try{
    $data = $auth->getUser($bearerToken);
    print_r($data); // show all user data returned
  } catch(Exception $e){
    echo $auth->getError();
}   

I receive back an error:

Client error: GET https://*****.supabase.co/auth/v1/user resulted in a 401 Unauthorized response:

"Invalid JWT: unable to parse or verify signature, signature is invalid".

Do you probably know what the problem could be?

Add support to stored procedures

Hello, great job! Do you mind adding support to call stored procedures?

This can be done by calling rest/v1/rpc/, it seems the library doesn't support this feature at the moment.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.