{"id":21831696,"url":"https://github.com/w99910/laravel-api-auth","last_synced_at":"2025-03-21T13:23:32.331Z","repository":{"id":59918701,"uuid":"540062198","full_name":"w99910/laravel-api-auth","owner":"w99910","description":null,"archived":false,"fork":false,"pushed_at":"2023-01-17T10:30:57.000Z","size":59,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-26T09:16:43.858Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/w99910.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"custom":"https://zawlintun.me/BinancePayQR.png"}},"created_at":"2022-09-22T16:03:51.000Z","updated_at":"2022-09-22T16:05:35.000Z","dependencies_parsed_at":"2023-02-10T09:15:40.272Z","dependency_job_id":null,"html_url":"https://github.com/w99910/laravel-api-auth","commit_stats":null,"previous_names":[],"tags_count":21,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w99910%2Flaravel-api-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w99910%2Flaravel-api-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w99910%2Flaravel-api-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/w99910%2Flaravel-api-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/w99910","download_url":"https://codeload.github.com/w99910/laravel-api-auth/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244804135,"owners_count":20513056,"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":[],"created_at":"2024-11-27T19:14:19.384Z","updated_at":"2025-03-21T13:23:32.307Z","avatar_url":"https://github.com/w99910.png","language":"PHP","funding_links":["https://zawlintun.me/BinancePayQR.png"],"categories":[],"sub_categories":[],"readme":"# Laravel Api Auth\n\nThis package provides basic api authorization and easy-to-use servicing your Models.\n\n- Using this package, you don't need to write your own authorization logic for your api.\n  Even if you don't want to, you can use actions classes to ease your own authorization.\n- You don't have to write your own query.\n  Instead of using `Post::whereBetween(...)-\u003eorderByDesc(...)-\u003eget()`, you can use like\n  ```php\n  PostService::get([\n    'startDate' =\u003e '2022-01-01',\n    'endDate' =\u003e '2022-06-01',\n    'orderBy' =\u003e 'date',\n    'isDesc' =\u003e true,\n  ])\n  ```\n\n## Table Of Contents\n\n- [Installation](#installation)\n- [Publish config file](#publish-config-file)\n- [Authorization](#authorization)\n    - [Manually Login and Register](#manually-login-and-register)\n- [Servicing](#servicing)\n    - [Why you would need this?](#why-you-would-need-this)\n    - [How to use?](#how-to-use-it)\n- [Caching Response](#caching-response)\n- [License](#license)\n- [Conclusion](#conclusion)\n\n## Installation\n\n```bash\n$ composer require zlt/laravel-api-auth\n```\n\n## Publish config file\n\n```bash\n$ php artisan vendor:publish --provider=\"Zlt\\LaravelApiAuth\\LaravelApiAuthServiceProvider\"\n```\n\nThe following are the default config.\n\n```php\n\u003c?php\n\nreturn [\n    /*\n     * If true, `api/login` and `api/register` routes will be registered.\n     */\n    'shouldIncludeRoutes' =\u003e true,\n\n    /*\n     * Define your auth model\n     */\n    'authUser' =\u003e App\\Models\\User::class,\n\n    /*\n     * If true, action will try to create token in registration and appending token in login.\n     */\n    'enableSanctum' =\u003e true,\n\n    /*\n     * In some cases, you might want to use other column than `email`\n     */\n    'username' =\u003e 'email',\n\n    /*\n     * Validation rule for password in registration\n     */\n    'password:rule' =\u003e 'required|min:8',\n\n    /*\n     * Determine if api routes should have `application/json` as Accept header\n     */\n    'addApplicationJsonHeader' =\u003e true,\n\n    /**\n     * When using `Zlt\\LaravelApiAuth\\Utils\\CanCache` trait, you can define cache prefix here.\n     */\n    'cache-prefix' =\u003e null,\n];\n\n```\n\n## Authorization\n\nThere are already api routes defined for you to authorize a user such as `/api/login`, `/api/register`\nand `/api/delete`.\nIn order to disable those routes, you can set the `shouldIncludeRoutes` option to `false` in\nthe `config/laravel-api-auth.php` file.\n\n### Manually Login and Register\n\n- #### Login a user\n  `Zlt\\LaravelApiAuth\\Actions\\Login:class` can be used to log user in.\n    - Create instance.\n    - invoke the instance `values` as parameter. Let action handle validation and checking credentials.\n    - `Zlt\\LaravelApiAuth\\Support\\ApiResponse` will be always returned with corresponding message, additional data and\n      status code.\n\n    ```php\n    $values = ['email'=\u003e'mail@mail.com','password' =\u003e '12345678'];\n    $login = new Zlt\\LaravelApiAuth\\Actions\\Login;\n    $response = $login(values: $values);\n    ```\n\n- #### Registering a user\n  `Zlt\\LaravelApiAuth\\Actions\\Register::class` can be used to register a user.\n    - Create instance.\n    - invoke the instance `values` as parameter. Let action handle validation and checking credentials.\n    - `Zlt\\LaravelApiAuth\\Support\\ApiResponse` will be always returned with corresponding message, additional data and\n      status code.\n    ```php\n    $values = ['email'=\u003e'mail@mail.com','password' =\u003e '12345678'];\n    $register = new Zlt\\LaravelApiAuth\\Actions\\Register;\n    $response = $register(values:$values);\n    ```\n- ### Deleting a user\n  `Zlt\\LaravelApiAuth\\Actions\\Delete::class` can be used to delete a user.\n    - Create instance.\n    - invoke the instance `values` as parameter. Let action handle validation and checking credentials.\n    - `Zlt\\LaravelApiAuth\\Support\\ApiResponse` will be always returned with corresponding message, additional data and\n      status code.\n  ```php\n  $values = ['email'=\u003e'mail@mail.com'];\n  $delete = new Zlt\\LaravelApiAuth\\Actions\\Delete;\n  $response = $delete($values);\n  ```\n\n## Servicing\n\n### Why you would need this?\n\nThe idea of servicing is to provide a easy-to-use way to build database query and execute it.\n\nFor example, you have a `Post` model and you want to build query instead of using\nlike `Post::whereBetween('date',['2022-01-01','2022-06-01'])-\u003eorderByDesc('date')-\u003eget()`. Then you can use the\nfollowing service:\n\n```php\n\u003c?php\n\nnamespace App\\Services;\n\nuse App\\Models\\Post;\nuse Zlt\\LaravelApiAuth\\Enums\\Operator;\nuse Zlt\\LaravelApiAuth\\Services\\BaseService;\nuse Zlt\\LaravelApiAuth\\Support\\QueryableColumn;\n\n/**\n * @method static ApiResponse get(array $values);\n * @method static ApiResponse count(array $values);\n */\nclass PostService extends BaseService\n{\n    public function __construct()\n    {\n        $this-\u003eregisterQueryColumn(QueryableColumn::from(\n            'date',\n            ['startDate', 'endDate'],\n            'date_format:Y-m-d|required_with:startDate|required_with:endDate',\n            Operator::BETWEEN,\n        ));\n\n        parent::__construct(Post::query());\n    }\n\n    static function getInstance(): static\n    {\n        return new static();\n    }\n}\n```\n\nThen call static method `get` or `count` to get the result.\n\n```php\nPostService::get([\n    'startDate' =\u003e '2022-01-01',\n    'endDate' =\u003e '2022-06-01',\n    'orderBy' =\u003e 'date',\n    'isDesc' =\u003e true,\n]);\n\nPostService::count([\n    'startDate' =\u003e '2022-01-01',\n    'endDate' =\u003e '2022-06-01',\n    'orderBy' =\u003e 'date',\n    'isDesc' =\u003e true,\n]);\n```\n\n### How to use it?\n\n- First, you need to extend `Zlt\\LaravelApiAuth\\Services\\BaseService` and implement the `getInstance` method.\n  ```php\n  class YourService extends Zlt\\LaravelApiAuth\\Services\\BaseService{\n  \n    static function getInstance(): static\n    {\n       \n    }\n  }\n  ```\n- Then, you need to pass your `Builder` instance to constructor or inside the constructor.\n  ```php\n  // Pass to constructor\n  static function getInstance(): static\n  {\n     return new static(YourModel::query());\n  }\n  \n  // Inside constructor\n  public function __construct()\n  {\n     parent::__construct(YourModel::query());\n  }\n  ```\n- You can use some built-in features offered by package.\n    - `orderBy`\n    - `limit`\n    - `offset`\n    - `hiddenFields`\n    - `selectedFields`\n\n  For example,\n    ```php\n    PostService::get([\n        'orderBy' =\u003e 'date',\n        'isDesc' =\u003e true,\n        'limit' =\u003e 10,\n        'offset' =\u003e 0,\n        'hiddenFields' =\u003e ['id','created_at','updated_at'],\n        'selectedFields' =\u003e ['title','date'],\n    ]);\n    ```\n- You can register queryable column and cast the value before using in query.\n  For example, you want to get posts between two dates. ( Assume there is `date` column)\n  ```php\n  // Register queryable column in constructor\n  class YourService extends Zlt\\LaravelApiAuth\\Services\\BaseService{\n  \n    public function __construct()\n    {\n        $this-\u003eregisterQueryColumn(QueryableColumn::from(\n            'date', // DB Column\n            ['startDate', 'endDate'], // Request Parameters\n            'date_format:Y-m-d|required_with:startDate|required_with:endDate', // Validation Rule\n            Operator::BETWEEN, // Operator\n        ));\n        parent::__construct(YourModel::query());\n    }\n  }\n \n  // And then \n  YourService::get([\n      'startDate' =\u003e '2022-01-01',\n      'endDate' =\u003e '2022-06-01',\n  ]);\n  ```\n\n  You can also cast the value before using in query.\n  ```php\n  public function __construct()\n  {\n      $this-\u003eregisterQueryColumn(QueryableColumn::from(\n          'date', // DB Column\n          ['startDate', 'endDate'], // Request Parameters\n          'date_format:Y-m-d|required_with:startDate|required_with:endDate', // Validation Rule\n          Operator::BETWEEN, // Operator\n          function ($value, $parameter) {\n                $date = new Carbon($value);\n                if ($parameter === 'startDate') {\n                    return $date-\u003estartOfDay()-\u003etimestamp;\n                }\n                return $date-\u003eendOfDay()-\u003etimestamp;\n            }\n      ));\n      parent::__construct(YourModel::query());\n  }\n  ```\n\n## Caching response\n\nThis package also offers a trait to cache response.\n\n```php\nuse Zlt\\LaravelApiAuth\\Utils\\CanCache;\n\nclass YourClass {\n\n    use CanCache;\n  \n    public function yourMethod(Request $request){\n        if($this-\u003echeckIfCacheKeyExists($request)){\n            return $this-\u003egetCacheData($request);\n        }\n        $response = $this-\u003ecomputeData();\n        $this-\u003estoreCache($request,$response);\n        return $response;\n    }\n}\n```\n\n## License\n\n[MIT](LICENSE)\n\n## Conclusion\n\nWhy I created this package is because I needed to use such features in my projects. But now I think it would probably\nhelp\nothers too. So I decided to share it with you. I hope you find it useful.\n\nFeel free to contribute to this package.\n\nIf you find it useful, please give it a star or buy me a coffee via Binance.\n\n\u003cimg src=\"https://zawlintun.me/BinancePayQR.png\" alt=\"binancePayQR\" width=\"200\"/\u003e\n\nCheers!\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fw99910%2Flaravel-api-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fw99910%2Flaravel-api-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fw99910%2Flaravel-api-auth/lists"}