{"id":14968848,"url":"https://github.com/rafaelwendel/phpsupabase","last_synced_at":"2025-04-04T11:13:41.377Z","repository":{"id":44458227,"uuid":"426806606","full_name":"rafaelwendel/phpsupabase","owner":"rafaelwendel","description":"PHP Client to use Supabase ","archived":false,"fork":false,"pushed_at":"2024-08-09T18:15:41.000Z","size":98,"stargazers_count":202,"open_issues_count":9,"forks_count":20,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-03-28T10:08:37.455Z","etag":null,"topics":["client","php","supabase"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rafaelwendel.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-10T23:14:08.000Z","updated_at":"2025-03-17T02:29:43.000Z","dependencies_parsed_at":"2024-08-09T19:52:22.071Z","dependency_job_id":null,"html_url":"https://github.com/rafaelwendel/phpsupabase","commit_stats":{"total_commits":111,"total_committers":2,"mean_commits":55.5,"dds":0.009009009009009028,"last_synced_commit":"0bd665b53b36b0299e6fecf8a5085f4e886e67c5"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rafaelwendel%2Fphpsupabase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rafaelwendel%2Fphpsupabase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rafaelwendel%2Fphpsupabase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rafaelwendel%2Fphpsupabase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rafaelwendel","download_url":"https://codeload.github.com/rafaelwendel/phpsupabase/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247166168,"owners_count":20894654,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client","php","supabase"],"created_at":"2024-09-24T13:40:42.012Z","updated_at":"2025-04-04T11:13:41.349Z","avatar_url":"https://github.com/rafaelwendel.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PHPSupabase\n\nPHPSupabase is a library written in php language, which allows you to use the resources of a project created in Supabase ([supabase.io](https://supabase.io)), through integration with its Rest API.\n\n## Content\n\n- [About Supabase](#about-supabase)\n- [PHPSupabase Features](#phpsupabase-features)\n- [Instalation \u0026 Loading](#instalation-\u0026-features)\n- [How to use](#how-to-use)\n    - [Auth Class](#auth-class)\n        - [Create a new user with email and password](#create-a-new-user-with-email-and-password)\n        - [Sign in with email and password](#sign-in-with-email-and-password)\n        - [Get the data of the logged in user](#get-the-data-of-the-logged-in-user)\n        - [Update user data](#update-user-data)\n    - [Database class](#database-class)\n        - [Insert data](#insert-data)\n        - [Update data](#update-data)\n        - [Delete data](#delete-data)\n        - [Fetch data](#fetch-data)\n        - [Comparison operators](#comparison-operators)\n    - [QueryBuilder class](#querybuilder-class)\n\n## About Supabase\n\nSupabase 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.\n\n## PHPSupabase Features\n\n- Create and manage users of a Supabase project\n- Manage user authentication (with email/password, magic links, among others)\n- Insert, Update, Delete and Fetch data in Postgres Database (by Supabase project Rest API)\n- A QueryBuilder class to filter project data in uncomplicated way\n\n## Instalation \u0026 loading\n\nPHPSupabase is available on [Packagist](https://packagist.org/packages/rafaelwendel/phpsupabase), and instalation via [Composer](https://getcomposer.org) is the recommended way to install it. Add the follow line to your `composer.json` file:\n\n```json\n\"rafaelwendel/phpsupabase\" : \"^0.0.1\"\n```\n\nor run\n\n```sh\ncomposer require rafaelwendel/phpsupabase\n```\n\n## How to use\n\nTo 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` \u0026 `/auth/v1`, but since version `0.0.5` the definition of one of these suffixes is optional)\n\nTo start, let's instantiate the `Service()` class. We must pass the `API key` and `url` in the constructor\n\n```php\n\u003c?php\n\nrequire \"vendor/autoload.php\";\n\n$service = new PHPSupabase\\Service(\n    \"YOUR_API_KEY\", \n    \"https://aaabbbccc.supabase.co\"\n);\n\n//In versions 0.0.4 or earlier it is necessary to set the suffix\n$service = new PHPSupabase\\Service(\n    \"YOUR_API_KEY\", \n    \"https://aaabbbccc.supabase.co/auth/v1\" // or https://aaabbbccc.supabase.co/rest/v1\n);\n```\n\nThe `Service` class abstracts the actions with the project's API and also provides the instances of the other classes (`Auth`, `Database` and `QueryBuilder`).\n\n### Auth class\n\nLet's instantiate an object of the `Auth` class\n\n```php\n\n$auth = $service-\u003ecreateAuth();\n```\n\nThe `$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.\n\n#### Create a new user with email and password\n\nSee how to create a new user with `email` and `password`.\n\n```php\n\n$auth = $service-\u003ecreateAuth();\n\ntry{\n    $auth-\u003ecreateUserWithEmailAndPassword('newuser@email.com', 'NewUserPassword');\n    $data = $auth-\u003edata(); // get the returned data generated by request\n    echo 'User has been created! A confirmation link has been sent to the '. $data-\u003eemail;\n}\ncatch(Exception $e){\n    echo $auth-\u003egetError();\n}\n```\n\nThis 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.\n\nIn the third parameter of the `createUserWithEmailAndPassword` method you can pass an array containing the `user_metadata` to be saved (Ex: `name` and `age`)\n\n```php\n$user_metadata = [\n    'name' =\u003e 'Lebron James',\n    'age' =\u003e '34'\n];\n$auth-\u003ecreateUserWithEmailAndPassword('lebron@email.com', 'LebronPassword', $user_metadata);\n```\n\n#### Sign in with email and password\n\nNow 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\n\n```php\n\n$auth = $service-\u003ecreateAuth();\n\ntry{\n    $auth-\u003esignInWithEmailAndPassword('user@email.com', 'UserPassword');\n    $data = $auth-\u003edata(); // get the returned data generated by request\n\n    if(isset($data-\u003eaccess_token)){\n        $userData = $data-\u003euser; //get the user data\n        echo 'Login successfully for user ' . $userData-\u003eemail;\n\n        //save the $data-\u003eaccess_token in Session, Cookie or other for future requests.\n    }\n}\ncatch(Exception $e){\n    echo $auth-\u003egetError();\n}\n```\n\n#### Get the data of the logged in user\n\nTo get the user data, you need to have the `access_token` (Bearer Token), which was returned in the login action.\n\n```php\n\n$auth = $service-\u003ecreateAuth();\n$bearerToken = 'THE_ACCESS_TOKEN';\n\ntry{\n    $data = $auth-\u003egetUser($bearerToken);\n    print_r($data); // show all user data returned\n}\ncatch(Exception $e){\n    echo $auth-\u003egetError();\n}\n```\n\n#### Update user data\n\nIt 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).\n\nThe `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`.\n\nAn example of how to save/update two new meta data (`first_name` and `last_name`) for the user.\n\n```php\n\n$auth = $service-\u003ecreateAuth();\n$bearerToken = 'THE_ACCESS_TOKEN';\n\n$newUserMetaData = [\n    'first_name' =\u003e 'Michael',\n    'last_name'  =\u003e 'Jordan'\n];\n\ntry{\n    //the parameters 2 (email) and 3(password) are null because this data will not be changed\n    $data = $auth-\u003eupdateUser($bearerToken, null, null, $newUserMetaData);\n    print_r($data); // show all user data returned\n}\ncatch(Exception $e){\n    echo $auth-\u003egetError();\n}\n```\nNote that in the array returned now, the keys `first_name` and `last_name` were added to `user_metadata`.\n\n### Database class\n\nThe Database class provides features to perform actions (insert, update, delete and fetch) on the Postgre database tables provided by the Supabase project.\n\nFor the samples below, consider the following database structure:\n\n```sql\ncategories (id INT AUTO_INCREMENT, categoryname VARCHAR(32))\nproducts (id INT AUTO_INCREMENT, productname VARCHAR(32), price FLOAT, categoryid INT)\n```\n\nThe 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`).\n\nLet's create an object to work with the `categories` table:\n\n```php\n$db = $service-\u003einitializeDatabase('categories', 'id');\n```\n\nThrough the `db` variable it is possible to perform the actions on the `categories` table.\n\nNOTE: If Row Level Security (RLS) is enabled in the used table, pass the `bearerToken` to the `Service` object:\n\n```php\n$bearerToken = 'THE_ACCESS_TOKEN'; //returned in the login action.\n$db = $service-\u003esetBearerToken($bearerToken)-\u003einitializeDatabase('categories', 'id');\n```\n\n#### Insert data\n\nInserting a new record in the `categories` table:\n\n```php\n$db = $service-\u003einitializeDatabase('categories', 'id');\n\n$newCategory = [\n    'categoryname' =\u003e 'Video Games'\n];\n\ntry{\n    $data = $db-\u003einsert($newCategory);\n    print_r($data); //returns an array with the new register data\n    /*\n        Array\n        (\n            [0] =\u003e stdClass Object\n                (\n                    [id] =\u003e 1\n                    [categoryname] =\u003e Video Games\n                )\n\n        )\n    */\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nNow let's insert a new product from category `1 - Video Games`:\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\n$newProduct = [\n    'productname' =\u003e 'XBOX Series S',\n    'price'       =\u003e '299.99',\n    'categoryid'  =\u003e '1' //Category \"Video Games\"\n];\n\ntry{\n    $data = $db-\u003einsert($newProduct);\n    print_r($data); //returns an array with the new register data\n    /*\n        Array\n        (\n            [0] =\u003e stdClass Object\n                (\n                    [id] =\u003e 1\n                    [productname] =\u003e XBOX Series S\n                    [price] =\u003e 299.99\n                    [categoryid] =\u003e 1\n                )\n        )\n    */\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\n#### Update data\n\nTo 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).\n\nIn 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\"):\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\n$updateProduct = [\n    'productname' =\u003e 'XBOX Series S 512GB',\n    'price'       =\u003e '319.99'\n];\n\ntry{\n    $data = $db-\u003eupdate('1', $updateProduct); //the first parameter ('1') is the product id\n    print_r($data); //returns an array with the product data (updated)\n    /*\n        Array\n        (\n            [0] =\u003e stdClass Object\n                (\n                    [id] =\u003e 1\n                    [productname] =\u003e XBOX Series S 512GB\n                    [price] =\u003e 319.99\n                    [categoryid] =\u003e 1\n                )\n        )\n    */\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\n#### Delete data\n\nTo 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.\n\nThe following code deletes the product of `id=1` in the `products` table:\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\ntry{\n    $data = $db-\u003edelete('1'); //the parameter ('1') is the product id\n    echo 'Product deleted successfully';\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n#### Fetch data\n\nThe following methods for fetching data are available in the `Database` class:\n\n- `fetchAll()`: fetch all table records;\n- `findBy(string $column, string $value)`: fetch records filtereds by a column/value (using the `=` operator);\n- `findByLike(string $column, string $value)`: fetch records filtereds by a column/value (using the `LIKE` operator);\n- `join(string $foreignTable, string $foreignKey)`: make a `join` between the seted table and another table related and fetch records;\n- `createCustomQuery(array $args)`: build a custom SQL query. The following `keys` are valid for the `args` argument:\n    - `select`\n    - `from`\n    - `join`\n    - `where`\n    - `limit`\n    - `range`\n\nAll the mentioned methods return the self instance of `Database` class. To access the fetched data, call the `getResult` method.\n\nSee some examples:\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\ntry{\n    $listProducts = $db-\u003efetchAll()-\u003egetResult(); //fetch all products\n    foreach ($listProducts as $product){\n        echo $product-\u003eid . ' - ' . $product-\u003eproductname . '($' . $product-\u003eprice . ') \u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nNow, an example using the `findBy` method:\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\ntry{\n    $listProducts = $db-\u003efindBy('productname', 'PlayStation 5')-\u003egetResult(); //Searches for products that have the value \"PlayStation 5\" in the \"productname\" column\n    foreach ($listProducts as $product){\n        echo $product-\u003eid . ' - ' . $product-\u003eproductname . '($' . $product-\u003eprice . ') \u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nSearching for `products` and adding a join with the `categories` table:\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\ntry{\n    $listProducts = $db-\u003ejoin('categories', 'id')-\u003egetResult(); //fetch data from \"products\" JOIN \"categories\"\n    foreach ($listProducts as $product){\n        //SHOW \"productname\" - \"categoryname\"\n        echo $product-\u003eproductname . ' - ' . $product-\u003ecategories-\u003ecategoryname . '\u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nAn example of a custom query to search `id,productname,price` for all `products` \"JOIN\" `categories` filtering by `price` (`price` greater than `200.00`):\n\n```php\n$db = $service-\u003einitializeDatabase('products', 'id');\n\n$query = [\n    'select' =\u003e 'id,productname,price',\n    'from'   =\u003e 'products',\n    'join'   =\u003e [\n        [\n            'table' =\u003e 'categories',\n            'tablekey' =\u003e 'id'\n        ]\n    ],\n    'where' =\u003e \n    [\n        'price' =\u003e 'gt.200' //\"gt\" means \"greater than\" (\u003e)\n    ]\n];\n\ntry{\n    $listProducts = $db-\u003ecreateCustomQuery($query)-\u003egetResult();\n    foreach ($listProducts as $product){\n        echo $product-\u003eid . ' - ' . $product-\u003eproductname . '($' . $product-\u003eprice . ') \u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nOther examples for custom query:\n\n```php\n//products with price \u003e 200 AND productname LIKE '%n%'\n$query = [\n    'select' =\u003e 'id,productname,price',\n    'from'   =\u003e 'products',\n    'where' =\u003e \n    [\n        'price' =\u003e 'gt.200', //\"gt\" means \"greater than\" (\u003e)\n        'productname' =\u003e 'like.%n%' //like operator\n    ]\n];\n\n//products with categoryid = 1\n$query = [\n    'select' =\u003e 'id,productname,price',\n    'from'   =\u003e 'products',\n    'where' =\u003e \n    [\n        'categoryid' =\u003e 'eq.1', //\"eq\" means \"equal\" (=)\n    ]\n];\n\n//products with price \u003c 1000 LIMIT 4 results\n$query = [\n    'select' =\u003e 'id,productname,price',\n    'from'   =\u003e 'products',\n    'where' =\u003e \n    [\n        'price' =\u003e 'lt.1000', //\"lt\" means \"less than\" (\u003c)\n    ],\n    'limit' =\u003e 4 //4 first rows\n];\n```\n\n#### Comparison operators\n\nThe main operators available for the `where` clause:\n- `eq`: equal\n- `neq`: not equal\n- `gt`: greater than\n- `gte`: greater than or equal\n- `lt`: less than\n- `lte`: less than or equal\n- `like`: search for a specified pattern in a column\n- `ilike`: search for a specified pattern in a column (case insensitive)\n\nOther operators available:\n- `is`\n- `in`\n- `cs`\n- `cd`\n- `sl`\n- `sr`\n- `nxl`\n- `nxr`\n- `adj`\n- `ov`\n- `fts`\n- `plfts`\n- `phfts`\n- `wfts`\n- `not.eq`\n- `not.neq`\n- `not.gt`\n- `not.gte`\n- `not.lt`\n- `not.lte`\n- `not.like`\n- `not.ilike`\n- `not.is`\n- `not.in`\n- `not.cs`\n- `not.cd`\n- `not.sl`\n- `not.sr`\n- `not.nxl`\n- `not.nxr`\n- `not.adj`\n- `not.ov`\n- `not.fts`\n- `not.plfts`\n- `not.phfts`\n- `not.wfts`\n\n### QueryBuilder class\n\nThe QueryBuilder class provides methods for dynamically building SQL queries. It is instantiated from the `service` object.\n\n```php\n$query = $service-\u003einitializeQueryBuilder();\n```\n\nNOTE: If Row Level Security (RLS) is enabled on any of the tables used, pass the `bearerToken` to the `Service` object:\n\n```php\n$bearerToken = 'THE_ACCESS_TOKEN'; //returned in the login action.\n$query = $service-\u003esetBearerToken($bearerToken)-\u003einitializeQueryBuilder();\n```\n\nAvailable methods:\n\n- `select(string $select)`: the fields (comma separated) or `*`\n- `from(string $from)`: the table\n- `join(string $table, string $tablekey, string $select = null)`: related table\n- `where(string $column, string $value)`: conditions\n- `limit(int $limit)`: limit rows\n- `order(string $order)`: the \"order by\" field\n- `range(string $range)`: results range (E.g. \"0-3\")\n\nAll 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.\n\nAn example to fetch all data from the `products` table:\n\n```php\n$query = $service-\u003einitializeQueryBuilder();\n\ntry{\n    $listProducts = $query-\u003eselect('*')\n                -\u003efrom('products')\n                -\u003eexecute()\n                -\u003egetResult();\n    foreach ($listProducts as $product){\n        echo $product-\u003eid . ' - ' . $product-\u003eproductname . '($' . $product-\u003eprice . ') \u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\nAn example to fetch all data from the `products` \"JOIN\" `categories`:\n\n```php\n$query = $service-\u003einitializeQueryBuilder();\n\ntry{\n    $listProducts = $query-\u003eselect('*')\n                -\u003efrom('products')\n                -\u003ejoin('categories', 'id')\n                -\u003eexecute()\n                -\u003egetResult();\n    foreach ($listProducts as $product){\n        echo $product-\u003eid . ' - ' . $product-\u003eproductname . '($' . $product-\u003eprice . ') - '. $product-\u003ecategories-\u003ecategoryname .' \u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nFetch `products` with `categoryid=1` and `price\u003e200` order by `price`:\n\n```php\n$query = $service-\u003einitializeQueryBuilder();\n\ntry{\n    $listProducts = $query-\u003eselect('*')\n                -\u003efrom('products')\n                -\u003ejoin('categories', 'id')\n                -\u003ewhere('categoryid', 'eq.1') //eq -\u003e equal\n                -\u003ewhere('price', 'gt.200') // gt -\u003e greater than\n                -\u003eorder('price.asc') //\"price.desc\" for descending\n                -\u003eexecute()\n                -\u003egetResult();\n    foreach ($listProducts as $product){\n        echo $product-\u003eid . ' - ' . $product-\u003eproductname . '($' . $product-\u003eprice . ') - '. $product-\u003ecategories-\u003ecategoryname .' \u003cbr /\u003e';\n    }\n}\ncatch(Exception $e){\n    echo $e-\u003egetMessage();\n}\n```\n\nSome of the operators to be used in the `where` method can be seen in the [Comparison operators](#comparison-operators) section.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frafaelwendel%2Fphpsupabase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frafaelwendel%2Fphpsupabase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frafaelwendel%2Fphpsupabase/lists"}