{"id":22944333,"url":"https://github.com/clickbar/ag-grid-laravel","last_synced_at":"2025-08-12T22:31:56.840Z","repository":{"id":190409340,"uuid":"682458431","full_name":"clickbar/ag-grid-laravel","owner":"clickbar","description":"An AG Grid Server Side Adapter for Laravel","archived":false,"fork":false,"pushed_at":"2024-01-24T10:20:17.000Z","size":204,"stargazers_count":16,"open_issues_count":2,"forks_count":4,"subscribers_count":5,"default_branch":"main","last_synced_at":"2024-11-16T08:06:44.051Z","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/clickbar.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-08-24T08:03:04.000Z","updated_at":"2024-07-05T10:18:22.000Z","dependencies_parsed_at":"2023-08-24T15:04:16.795Z","dependency_job_id":"a361d929-4f05-4b17-bccd-80e5ffc8c5df","html_url":"https://github.com/clickbar/ag-grid-laravel","commit_stats":null,"previous_names":["clickbar/ag-grid-laravel"],"tags_count":3,"template":false,"template_full_name":"spatie/package-skeleton-laravel","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clickbar%2Fag-grid-laravel","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clickbar%2Fag-grid-laravel/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clickbar%2Fag-grid-laravel/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clickbar%2Fag-grid-laravel/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/clickbar","download_url":"https://codeload.github.com/clickbar/ag-grid-laravel/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229711198,"owners_count":18112094,"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-12-14T14:17:41.661Z","updated_at":"2024-12-14T14:17:42.429Z","avatar_url":"https://github.com/clickbar.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AG Grid server-side adapter for Laravel\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/clickbar/ag-grid-laravel.svg?style=flat-square)](https://packagist.org/packages/clickbar/ag-grid-laravel)\n[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/clickbar/ag-grid-laravel/run-tests.yml?branch=main\u0026label=tests\u0026style=flat-square)](https://github.com/clickbar/ag-grid-laravel/actions?query=workflow%3Arun-tests+branch%3Amain)\n[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/clickbar/ag-grid-laravel/fix-php-code-style-issues.yml?branch=main\u0026label=code%20style\u0026style=flat-square)](https://github.com/clickbar/ag-grid-laravel/actions?query=workflow%3A\"Fix+PHP+code+style+issues\"+branch%3Amain)\n[![Total Downloads](https://img.shields.io/packagist/dt/clickbar/ag-grid-laravel.svg?style=flat-square)](https://packagist.org/packages/clickbar/ag-grid-laravel)\n\nThis package implements a server-side adapter for [AG Grid](https://www.ag-grid.com/) with support for filtering, sorting, exporting and server-side selection.\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require clickbar/ag-grid-laravel\n```\n\nYou can publish the config file with:\n\n```bash\nphp artisan vendor:publish --tag=\"ag-grid-laravel-config\"\n```\n\nThis is the contents of the published config file:\n\n```php\nreturn [\n    /*\n     * The class that contains the provider for determining the timezone \n     * to use for DateTime formatting in exports.\n     */\n    'export_timezone_provider' =\u003e \\Clickbar\\AgGrid\\AgGridDefaultExportTimezoneProvider::class\n];\n```\n\n## Usage\n\n### Querying a resource\n\nSimply accept an `AgGridGetRowsRequest` in your controller and return an instance of `AgGridQueryBuilder` for the model that you want to query. \nFiltering, sorting and exporting is handled automatically for you. You may also pass a JSON resource to the query builder to wrap your models with.\n\n```php\nclass FlamingoGridController extends Controller\n{\n    public function __invoke(AgGridGetRowsRequest $request): AgGridQueryBuilder\n    {\n        $query = Flamingo::query()\n            -\u003ewith(['keeper'])\n            -\u003eorderByDesc('id');\n\n        return AgGridQueryBuilder::forRequest($request, $query)\n            -\u003eresource(FlamingoResource::class);\n    }\n}\n```\n\n### Set Filter Values\nWhen using AG Grid with the `serverSide` row model, you are responsible for providing the values for the set value filter (the frontend only knows a subset of the whole data and therefore cannot know all possible set values).\n\n```php\nclass FlamingoGridSetValuesController extends Controller\n{\n    public function __invoke(AgGridSetValuesRequest $request)\n    {\n        $query = Flamingo::query()\n            -\u003ewith(['keeper']);\n    \n        return AgGridQueryBuilder::forSetValuesRequest($request, $query)\n            -\u003etoSetValues(['*']);\n    }\n}\n```\nSee the `AgGridSetValuesRequest` class for the structure of the request.\n\n**IMPORTANT**  \nYou need to whitelist the columns the set filter values can be retrieved for. This can be done be providing an array with the columns/dotted relation:\n\n```php\n-\u003etoSetValues(['name', 'kepper.name']);\n```\n\nIf your model does not expose any relations or sensitive columns, you can also use `['*']` as wildcard.\n\nHere's an example for the frontend implementation:\n\n```typescript\nconst colDef = {\n    filterParams: {\n        excelMode: 'windows',\n        values: (parameters: SetFilterValuesFuncParams) =\u003e {\n            axios\n                .post('url',\n                    {\n                        column,\n                        filterModel: parameters.api.getFilterModel(),\n                    },\n                )\n                .then((response) =\u003e {\n                    parameters.success(response.data)\n                }).catch(() =\u003e {\n                parameters.success([])\n            })\n        },\n    },\n}\n```\n\n\n### Server-side select\n\nWhen using AG Grid with the `serverSide` row model, you can't just pass the selected IDs to the server when performing a batch operation.\nIn this case, you may pass the current selection state of the grid to the server and resolve the selection there.\n\nTo do so, add the following to your request:\n\n```php\nclass FeedFlamingosRequest extends FormRequest\n{\n    public function rules(): array\n    {\n        return [\n            'selection' =\u003e ['required', new AgGridSelection()],\n            'food_type' =\u003e ['required', 'string'],\n        ];\n    }\n}\n```\n\nIn your controller, use the `AgGridQueryBuilder` to resolve the selection:\n\n```php\nclass FeedFlamingosController extends Controller\n{\n    public function __invoke(FeedFlamingsRequest $request): AgGridQueryBuilder\n    {\n        $flamingos = AgGridQueryBuilder::forSelection($request-\u003evalidated('selection'))-\u003eget();\n\n        foreach($flamingos as $flamingo){\n            $flamingo-\u003efeed($request-\u003evalidated('food_type'));\n        }\n        \n        return $flamingos;\n    }\n}\n```\n\n### Exports\n\nTo enable server-side exports for your models, you must implement the `AgGridExportable` interface. \nAfter that, you can just pass `exportFormat` as part of your request to the grid controller and the library handles transforming your models into Excel, CSV, or TSV files.\n\n```php\nclass Flamingo extends Model implements AgGridExportable {\n\n    // ... your model definitions\n    \n    public static function getAgGridColumnDefinitions(): array\n    {\n        return [\n            new AgGridColumnDefinition(\n                'id',\n                __('ID'),\n            ),\n            new AgGridColumnDefinition(\n                'name',\n                __('Name'),\n            ),\n            new AgGridColumnDefinition(\n                'keeper_id',\n                __('Keeper'),\n                null,\n                fn ($data) =\u003e $data-\u003ekeeper-\u003ename,\n            ),\n            new AgGridColumnDefinition(\n                'created_at',\n                __('Created At'),\n                new AgGridDateFormatter(),\n            ),\n        ];\n    }\n\n}\n```\n\n### Custom Filters\n\nSometimes you may need to add custom filter scopes or other constraints to the query, \nwhich are not covered by the standard AG Grid filters. In this case, you may populate the `customFilters` object of the request with your own data.\nOn the backend side, your model must implement the `AgGridCustomFilterable` interface as shown below:\n\n```php\nclass Flamingo extends Model implements AgGridCustomFilterable {\n\n    use SoftDeletes;\n\n    // ... your model definitions\n    \n    public function applyAgGridCustomFilters(Builder $query, array $filters): void\n    {\n        $query-\u003ewhen($filters['showTrashed'] ?? false, function ($query) {\n            return $query-\u003ewithTrashed();\n        });\n    }\n}\n```\n\n## Type definitions\n\nYou may use the following Typescript type definitions as a reference \nfor implementing the requests on the frontend:\n\n```typescript\ninterface AgGridSelection {\n    rowModel: 'serverSide' | 'clientSide'\n    selectAll: boolean\n    toggledNodes: (string | number)[]\n    filterModel?: any\n    customFilters?: any\n}\n\ninterface AgGridGetRowsRequest extends IServerSideGetRowsRequest {\n    exportFormat?: 'excel' | 'csv' | 'tsv'\n    exportColumns?: string[]\n    customFilters?: any\n}\n\ninterface AgGridGetRowsResponse\u003cT\u003e {\n    total: number\n    data: T[]\n}\n```\n\n## Frontend implementation\n\nYou are free to use any frontend technology or framework of your choice.\nHowever, here are some examples that you may use as a starting point four your own implementation\n\n### Creating a DataSource\n\nIn order to use the server-side row model, you must create a data source. Here is an exemplary implementation of such one:\n\n```typescript\n function makeDataSource\u003cT\u003e(\n    url: string,\n    customFilters?: Record\u003cstring, any\u003e\n): IServerSideDatasource {\n    return {\n        // called by the grid when more rows are required\n        async getRows(parameters) {\n            const request = {\n                ...parameters.request,\n                customFilters,\n            }\n            // get data for request from server\n            try {\n                const response = await axios.post\u003cAgGridGetRowsResponse\u003cT\u003e\u003e(url, request)\n                parameters.success({\n                    rowData: response.data.data,\n                    rowCount: response.data.total,\n                })\n            } catch {\n                parameters.fail()\n            }\n        },\n    }\n}\n```\n\n### Triggering a server-side export\n\nServer-side exports are not implemented in AG Grid by default. However you can create a custom context menu or add a button somewhere that triggers the server-side export. The handler function may look something like this:\n\n```typescript\nasync function exportServerSide(grid: GridApi, format: 'excel' | 'csv' | 'tsv', onlySelected: boolean) {\n    // using a private api here to oget the ssrm parameters\n    const parameters = api.getModel().getRootStore().getSsrmParams()\n    // only request the visible columns\n    const cols = columnApi?.getAllDisplayedColumns().map((column) =\u003e column.getColId())\n    // download the file\n    const response = await axios.post(\n        props.dataSourceUrl!,\n        {\n            ...parameters,\n            ...(onlySelected ? api.getServerSideSelectionState() : {}),\n            exportFormat: format,\n            exportColumns: cols,\n        },\n        {\n            responseType: 'blob',\n        }\n    )\n    // create an object url from the response\n    const url = URL.createObjectURL(response.data)\n    // create a link to trigger the download\n    const a = document.createElement('a')\n    a.href = url\n    a.download = true\n    a.click()\n}\n```\n\n### Tracking selection state\n\nIf you want to use server-side selects, you must track the current selection and filter state of the grid:\n\n```typescript\n\n// use the selection in any batch requests to the server\nlet selection: AgGridSelection \n\nfunction onSelectionChanged(event: SelectionChangedEvent) {\n    if (event.api.getModel().getType() !== 'serverSide') {\n        throw new Error('Only the serverSide row model is supported.')\n    }\n    \n    const selectionState = event.api.getServerSideSelectionState() as IServerSideSelectionState\n    selection = {\n        rowModel: 'serverSide',\n        selectAll: selectionState.selectAll,\n        toggledNodes: selectionState.toggledNodes,\n        filterModel: event.api.getFilterModel()\n    }\n}\n\nfunction onFilterChanged(event: FilterChangedEvent) {\n    if (!selection) {\n        return\n    }\n    \n    selection.filterModel = event.api.getFilterModel()\n}\n```\n\n\n## Limitations\n\n- Only works with PostgreSQL as a storage backend due to some special SQL operators being used in set and json queries.\n- Does not support multiple conditions per filter (AND, OR)\n- Does not support server-side grouping for AG Grid's pivot mode\n- ~~Filtering for values in relations is only supported one level deep. E.g you can filter for `relation.value` but not `relation.otherRelation.value`~~\n\n## TODOs\n\n- [ ] Implement set filter for nested json fields\n- [ ] Implement multiple conditions per filter (`AND`, `OR`)\n- [ ] Add type-safe data structures for selection and request data\n- [ ] Test with mysql\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n## Credits\n\n- [clickbar. GmbH](https://github.com/clickbar)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fclickbar%2Fag-grid-laravel","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fclickbar%2Fag-grid-laravel","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fclickbar%2Fag-grid-laravel/lists"}