first commit

This commit is contained in:
Ariyutta
2026-08-07 10:47:09 +07:00
commit 1c094fbe7f
11630 changed files with 1580900 additions and 0 deletions
+26
View File
@@ -0,0 +1,26 @@
{
"branches": [
"main",
"master",
"*.x"
],
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
[
"@semantic-release/changelog",
{
"changelogFile": "CHANGELOG.md"
}
],
[
"@semantic-release/git",
{
"assets": [
"CHANGELOG.md"
]
}
],
"@semantic-release/github"
]
}
+122
View File
@@ -0,0 +1,122 @@
# [12.7.0](https://github.com/yajra/laravel-datatables/compare/v12.6.3...v12.7.0) (2026-02-20)
### Bug Fixes
* address phpstan and fork phplint checkout ([7c416ef](https://github.com/yajra/laravel-datatables/commit/7c416ef38347d23bc52eca5439f0889c4e493440))
* allow editing DT_RowIndex via editColumn ([fd161f0](https://github.com/yajra/laravel-datatables/commit/fd161f019f54fc13995bd4f2664f12e4f8aa3317))
* cast index column config for static analysis ([468f44c](https://github.com/yajra/laravel-datatables/commit/468f44ce845a4a40734eaaca9d5753095ced013a))
* **ci:** support fork PR checkout in pint workflow ([fe30c00](https://github.com/yajra/laravel-datatables/commit/fe30c005f15eccc5c1d5314199f35740a5ed2192))
* **ci:** update memcached action to v8 ([c9e7f15](https://github.com/yajra/laravel-datatables/commit/c9e7f15ea3833311664c3c818e1f29c2c23918f9))
### Features
* support LengthAwarePaginator engine ([b8f9bb3](https://github.com/yajra/laravel-datatables/commit/b8f9bb33189d069d81901af59c73057aa8d84abd))
## [12.6.3](https://github.com/yajra/laravel-datatables/compare/v12.6.2...v12.6.3) (2025-12-09)
### Bug Fixes
* [#3266](https://github.com/yajra/laravel-datatables/issues/3266), replace ConfigRepository's type helper methods with get() ([#3267](https://github.com/yajra/laravel-datatables/issues/3267)) ([b9e5f78](https://github.com/yajra/laravel-datatables/commit/b9e5f785851a21779b0c88c2b0eb5c02e9714a76))
* pint :robot: ([e74e6ce](https://github.com/yajra/laravel-datatables/commit/e74e6cea55d552dd4ac66483c73cc0029050f52e))
## [12.6.2](https://github.com/yajra/laravel-datatables/compare/v12.6.1...v12.6.2) (2025-12-02)
### Bug Fixes
* pint :robot: ([41a22c7](https://github.com/yajra/laravel-datatables/commit/41a22c7b52f4d154e6ee8b9c0834c51d20001c00))
* resolve PHPStan array key type errors ([3b5e668](https://github.com/yajra/laravel-datatables/commit/3b5e66832fd4c708c2fc6c4afffc12815c43b248))
## [12.6.1](https://github.com/yajra/laravel-datatables/compare/v12.6.0...v12.6.1) (2025-10-11)
### Bug Fixes
* value when mask uses "/" ([c771900](https://github.com/yajra/laravel-datatables/commit/c77190030c713e5b64c433bd161d9f33a210f22b))
# [12.6.0](https://github.com/yajra/laravel-datatables/compare/v12.5.1...v12.6.0) (2025-10-08)
### Bug Fixes
* replace unsafe eval() with Blade::render() in compileBlade ([7f46d58](https://github.com/yajra/laravel-datatables/commit/7f46d5872b0324493c28ecc8d848c182e88f30e0))
### Features
* add __isset() method to Request for attribute existence check ([33f44d4](https://github.com/yajra/laravel-datatables/commit/33f44d42d284d6ea0a054de81ad5a57c3050867d))
# Laravel DataTables
## CHANGELOG
### [Unreleased]
### v12.5.1 - 2025-10-02
- fix: ambiguous column in columnControlSearch() method #3252
### v12.5.0 - 2025-10-01
- feat: server-side column control #3251
- fix: https://github.com/yajra/laravel-datatables/issues/3250
### v12.4.2 - 2025-09-09
- fix: remove @internal annotation from orderColumn() method #3248
### v12.4.1 - 2025-08-29
- fix: request handling with playwright / pest 4 #3247
### v12.4.0 - 2025-06-15
- feat: add min search length control #3242
- fix: #3241
### v12.3.1 - 2025-06-10
- fix: support for array notation #3243
### v12.3.0 - 2025-05-17
- feat: add option to enable alias on relation tables #3234
- tests: Add tests to cover prefix detection #3239
- fix: https://github.com/yajra/laravel-datatables/pull/1782
### v12.2.1 - 2025-05-09
- fix: improve prefix detection #3238
- fix: #3237
### v12.2.0 - 2025-05-08
- feat: add relation resolver param to order callback #3232
- fix: improve column alias detection #3236
- fix: #3235
### v12.1.2 - 2025-05-07
- fix: prevent prefixing null/empty string #3233
### v12.1.1 - 2025-05-05
- fix: prevent ambiguous column names #3227
### v12.1.0 - 2025-04-28
- feat: add relation resolver param to filter callbacks #3229
### v12.0.1 - 2025-04-07
- fix: query results improvements #3224
### v12.0.0 - 2025-02-26
- feat: Laravel v12 Compatibility #3217
- fix: prevent duplicate table name errors #3216
[Unreleased]: https://github.com/yajra/laravel-datatables/compare/v12.0.0...master
+65
View File
@@ -0,0 +1,65 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others’ private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
Consequence: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
Community Impact: A violation through a single incident or series of actions.
Consequence: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
Community Impact: A serious violation of community standards, including sustained inappropriate behavior.
Consequence: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
Community Impact: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
Consequence: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
Community Impact Guidelines were inspired by Mozilla’s code of conduct enforcement ladder.
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2013-2022 Arjay Angeles <aqangeles@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+162
View File
@@ -0,0 +1,162 @@
# jQuery DataTables API for Laravel
[![Join the chat at https://gitter.im/yajra/laravel-datatables](https://badges.gitter.im/yajra/laravel-datatables.svg)](https://gitter.im/yajra/laravel-datatables?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/yajra)
[![Donate](https://img.shields.io/badge/donate-patreon-blue.svg)](https://www.patreon.com/bePatron?u=4521203)
[![Laravel 12](https://img.shields.io/badge/Laravel-12-orange.svg)](http://laravel.com)
[![Latest Stable Version](https://img.shields.io/packagist/v/yajra/laravel-datatables-oracle.svg)](https://packagist.org/packages/yajra/laravel-datatables-oracle)
[![Continuous Integration](https://github.com/yajra/laravel-datatables/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/yajra/laravel-datatables/actions/workflows/continuous-integration.yml)
[![Static Analysis](https://github.com/yajra/laravel-datatables/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/yajra/laravel-datatables/actions/workflows/static-analysis.yml)
[![Total Downloads](https://poser.pugx.org/yajra/laravel-datatables-oracle/d/total.svg)](https://packagist.org/packages/yajra/laravel-datatables-oracle)
[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://packagist.org/packages/yajra/laravel-datatables-oracle)
Laravel package for handling [server-side](https://www.datatables.net/manual/server-side) works of [DataTables](http://datatables.net) jQuery Plugin via [AJAX option](https://datatables.net/reference/option/ajax) by using Eloquent ORM, Fluent Query Builder or Collection.
```php
use Yajra\DataTables\Facades\DataTables;
return DataTables::eloquent(User::query())->toJson();
return DataTables::query(DB::table('users'))->toJson();
return DataTables::collection(User::all())->toJson();
return DataTables::make(User::query())->toJson();
return DataTables::make(DB::table('users'))->toJson();
return DataTables::make(User::all())->toJson();
```
## Sponsors
<table>
<body>
<tr>
<td>
<img src="https://www.npmjs.com/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci9lZDQwMmM1NjY2YjJlNjUxMTIyOWE4ZjM0NDdkNWMzYT9zaXplPTEwMCZkZWZhdWx0PXJldHJvIn0.aWU-snChAWu9abJV3dtBo-iy-2v_7JAxXUN1UHL_pDQ" height="50" alt="DataTables Logo">
</td>
<td>A big thank you to <a href="https://editor.datatables.net">DataTables</a> for supporting this project with a free DataTables Editor license.</td>
</tr>
</body>
</table>
<table>
<body>
<tr>
<td>
<img height="50" src="https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.png" alt="JetBrains logo.">
</td>
<td>A big thank you to <a href="https://jb.gg/OpenSource">JetBrains</a> for supporting this project with free open-source licenses of their IDEs.</td>
</tr>
</body>
</table>
<table>
<body>
<tr>
<td><img src="https://i.imgur.com/zR8rsqk.png" height="50" alt="Blackfire.io Logo"></td>
<td>A big thank you to <a href="https://blackfire.io/docs/introduction?utm_source=laravel-datatables&utm_medium=github_readme&utm_campaign=logo">Blackfire.io</a> for supporting this project with a free open-source license.</td>
</tr>
</body>
</table>
## Requirements
- [PHP >= 8.2](http://php.net/)
- [Laravel Framework](https://github.com/laravel/framework)
- [DataTables](http://datatables.net/)
## Documentations
- [Github Docs](https://github.com/yajra/laravel-datatables-docs)
- [Laravel DataTables Quick Starter](https://yajrabox.com/docs/laravel-datatables/master/quick-starter)
- [Laravel DataTables Documentation](https://yajrabox.com/docs/laravel-datatables)
## Laravel Version Compatibility
| Laravel | Package |
|:--------|:---------|
| 4.2.x | 3.x |
| 5.0.x | 6.x |
| 5.1.x | 6.x |
| 5.2.x | 6.x |
| 5.3.x | 6.x |
| 5.4.x | 7.x, 8.x |
| 5.5.x | 8.x |
| 5.6.x | 8.x |
| 5.7.x | 8.x |
| 5.8.x | 9.x |
| 6.x | 9.x |
| 7.x | 9.x |
| 8.x | 9.x |
| 9.x | 10.x |
| 10.x | 10.x |
| 11.x | 11.x |
| 12.x | 12.x |
## Quick Installation
### Option 1: Install all DataTables libraries
```bash
composer require yajra/laravel-datatables:"^12"
```
### Option 2: Install only this library
```bash
composer require yajra/laravel-datatables-oracle:"^12"
```
#### Service Provider & Facade (Optional on Laravel 5.5+)
Register the provider and facade on your `config/app.php` file.
```php
'providers' => [
...,
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
...,
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
```
#### Configuration (Optional)
```bash
php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"
```
And that's it! Start building out some awesome DataTables!
## Debugging Mode
To enable debugging mode, just set `APP_DEBUG=true` and the package will include the queries and inputs used when processing the table.
> [!IMPORTANT]
> Please ensure that the `APP_DEBUG` config is set to false when your app is in production.
## PHP ARTISAN SERVE BUG
Please avoid using `php artisan serve` when developing the package.
There are known bugs when using this where Laravel randomly returns a redirect and 401 (Unauthorized) if the route requires authentication and a 404 NotFoundHttpException on valid routes.
It is advised to use [Homestead](https://laravel.com/docs/5.4/homestead) or [Valet](https://laravel.com/docs/5.4/valet) when working with the package.
## Contributing
Please see [CONTRIBUTING](https://github.com/yajra/laravel-datatables/blob/master/.github/CONTRIBUTING.md) for details.
## Security
If you discover any security-related issues, please email [aqangeles@gmail.com](mailto:aqangeles@gmail.com) instead of using the issue tracker.
## Credits
- [Arjay Angeles](https://github.com/yajra)
- [bllim/laravel4-datatables-package](https://github.com/bllim/laravel4-datatables-package)
- [All Contributors](https://github.com/yajra/laravel-datatables/graphs/contributors)
## License
The MIT License (MIT). Please see [License File](https://github.com/yajra/laravel-datatables/blob/master/LICENSE.md) for more information.
+32
View File
@@ -0,0 +1,32 @@
# UPGRADE GUIDE
## Upgrading from v11.x to v12.x
- See PR https://github.com/yajra/laravel-datatables/pull/3216
## Upgrading from v9.x to v10.x
- `ApiResourceDataTable` support dropped, use `CollectionDataTable` instead.
- `queryBuilder()` deprecated method removed, use `query()` instead.
- Methods signature were updated to PHP8 syntax, adjust as needed if you extended the package.
## Upgrading from v8.x to v9.x
No breaking changes with only a bump on php version requirements.
## Upgrading from v7.x to v8.x
There are breaking changes since DataTables v8.x. If you are upgrading from v7.x to v8.x, please see [upgrade guide](https://yajrabox.com/docs/laravel-datatables/master/upgrade).
## Upgrading from v6.x to v7.x
- composer require yajra/laravel-datatables-oracle
- composer require yajra/laravel-datatables-buttons
- php artisan vendor:publish --tag=datatables --force
- php artisan vendor:publish --tag=datatables-buttons --force
## Upgrading from v5.x to v6.x
- Change all occurrences of `yajra\Datatables` to `Yajra\Datatables`. (Use Sublime's find and replace all for faster update).
- Remove `Datatables` facade registration.
- Temporarily comment out `Yajra\Datatables\DatatablesServiceProvider`.
- Update package version on your composer.json and use `yajra/laravel-datatables-oracle: ~6.0`
- Uncomment the provider `Yajra\Datatables\DatatablesServiceProvider`.
+93
View File
@@ -0,0 +1,93 @@
{
"name": "yajra/laravel-datatables-oracle",
"description": "jQuery DataTables API for Laravel",
"keywords": [
"yajra",
"laravel",
"dataTables",
"jquery"
],
"license": "MIT",
"authors": [
{
"name": "Arjay Angeles",
"email": "aqangeles@gmail.com"
}
],
"require": {
"php": "^8.2",
"illuminate/database": "^12",
"illuminate/filesystem": "^12",
"illuminate/http": "^12",
"illuminate/support": "^12",
"illuminate/view": "^12"
},
"require-dev": {
"algolia/algoliasearch-client-php": "^3.4.1",
"larastan/larastan": "^3.1.0",
"laravel/pint": "^1.14",
"laravel/scout": "^10.8.3",
"meilisearch/meilisearch-php": "^1.6.1",
"orchestra/testbench": "^10",
"rector/rector": "^2.0"
},
"suggest": {
"yajra/laravel-datatables-export": "Plugin for server-side exporting using livewire and queue worker.",
"yajra/laravel-datatables-buttons": "Plugin for server-side exporting of dataTables.",
"yajra/laravel-datatables-html": "Plugin for server-side HTML builder of dataTables.",
"yajra/laravel-datatables-fractal": "Plugin for server-side response using Fractal.",
"yajra/laravel-datatables-editor": "Plugin to use DataTables Editor (requires a license)."
},
"autoload": {
"psr-4": {
"Yajra\\DataTables\\": "src/"
},
"files": [
"src/helper.php"
]
},
"autoload-dev": {
"psr-4": {
"Yajra\\DataTables\\Tests\\": "tests/"
}
},
"extra": {
"branch-alias": {
"dev-master": "12.x-dev"
},
"laravel": {
"providers": [
"Yajra\\DataTables\\DataTablesServiceProvider"
],
"aliases": {
"DataTables": "Yajra\\DataTables\\Facades\\DataTables"
}
}
},
"config": {
"sort-packages": true,
"allow-plugins": {
"php-http/discovery": true
}
},
"scripts": {
"test": "./vendor/bin/phpunit",
"pint": "./vendor/bin/pint",
"rector": "./vendor/bin/rector",
"stan": "./vendor/bin/phpstan analyse --memory-limit=2G --ansi --no-progress --no-interaction --configuration=phpstan.neon.dist",
"pr": [
"@rector",
"@pint",
"@stan",
"@test"
]
},
"minimum-stability": "dev",
"prefer-stable": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/yajra"
}
]
}
@@ -0,0 +1,46 @@
<?php
namespace Yajra\DataTables;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class ApiResourceDataTable extends CollectionDataTable
{
/**
* Can the DataTable engine be created with these parameters.
*
* @param mixed $source
* @return bool
*/
public static function canCreate($source)
{
return $source instanceof AnonymousResourceCollection;
}
/**
* Factory method, create and return an instance for the DataTable engine.
*
* @param \Illuminate\Http\Resources\Json\AnonymousResourceCollection<array-key, array>|array $source
* @return ApiResourceDataTable|DataTableAbstract
*/
public static function create($source)
{
return parent::create($source);
}
/**
* CollectionEngine constructor.
*
* @param \Illuminate\Http\Resources\Json\AnonymousResourceCollection<array-key, array> $resourceCollection
*/
public function __construct(AnonymousResourceCollection $resourceCollection)
{
/** @var \Illuminate\Support\Collection<(int|string), array> $collection */
$collection = collect($resourceCollection)->pluck('resource');
$this->request = app('datatables.request');
$this->config = app('datatables.config');
$this->collection = $collection;
$this->original = $collection;
$this->columns = array_keys($this->serialize($collection->first()));
}
}
@@ -0,0 +1,339 @@
<?php
namespace Yajra\DataTables;
use Closure;
use Exception;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Yajra\DataTables\Utilities\Helper;
class CollectionDataTable extends DataTableAbstract
{
/**
* Collection object.
*
* @var \Illuminate\Support\Collection<array-key, array>
*/
public Collection $original;
/**
* The offset of the first record in the full dataset.
*/
private int $offset = 0;
/**
* CollectionEngine constructor.
*
* @param \Illuminate\Support\Collection<array-key, array> $collection
*/
public function __construct(public Collection $collection)
{
$this->request = app('datatables.request');
$this->config = app('datatables.config');
$this->original = $this->collection;
$this->columns = array_keys($this->serialize($this->collection->first()));
}
/**
* Serialize collection.
*/
protected function serialize(mixed $collection): array
{
return $collection instanceof Arrayable ? $collection->toArray() : (array) $collection;
}
/**
* Can the DataTable engine be created with these parameters.
*
* @param mixed $source
* @return bool
*/
public static function canCreate($source)
{
return is_array($source) || $source instanceof Collection;
}
/**
* Factory method, create and return an instance for the DataTable engine.
*
* @param AnonymousResourceCollection|array|\Illuminate\Support\Collection<array-key, array> $source
* @return static
*/
public static function create($source)
{
if (is_array($source)) {
$source = new Collection($source);
}
return parent::create($source);
}
/**
* Count results.
*/
public function count(): int
{
return $this->collection->count();
}
/**
* Perform column search.
*/
public function columnSearch(): void
{
for ($i = 0, $c = count($this->request->columns()); $i < $c; $i++) {
$column = $this->getColumnName($i);
if (is_null($column)) {
continue;
}
if (! $this->request->isColumnSearchable($i) || $this->isBlacklisted($column)) {
continue;
}
$regex = $this->request->isRegex($i);
$keyword = $this->request->columnKeyword($i);
$this->collection = $this->collection->filter(
function ($row) use ($column, $keyword, $regex) {
$data = $this->serialize($row);
/** @var string $value */
$value = Arr::get($data, $column);
if ($this->config->isCaseInsensitive()) {
if ($regex) {
return preg_match('/'.$keyword.'/i', $value) == 1;
}
return str_contains(Str::lower($value), Str::lower($keyword));
}
if ($regex) {
return preg_match('/'.$keyword.'/', $value) == 1;
}
return str_contains($value, $keyword);
}
);
}
}
/**
* Perform pagination.
*/
public function paging(): void
{
$offset = $this->request->start() - $this->offset;
$length = $this->request->length() > 0 ? $this->request->length() : 10;
$this->collection = $this->collection->slice($offset, $length);
}
/**
* Organizes works.
*
* @throws \Exception
*/
public function make(bool $mDataSupport = true): JsonResponse
{
try {
$this->validateMinLengthSearch();
$this->totalRecords = $this->totalCount();
if ($this->totalRecords) {
$results = $this->results();
$processed = $this->processResults($results, $mDataSupport);
$output = $this->transform($results, $processed);
$this->collection = collect($output);
$this->ordering();
$this->filterRecords();
$this->paginate();
$this->revertIndexColumn($mDataSupport);
}
return $this->render($this->collection->values()->all());
} catch (Exception $exception) {
return $this->errorResponse($exception);
}
}
/**
* Get results.
*
* @return \Illuminate\Support\Collection<array-key, array>
*/
public function results(): Collection
{
return $this->collection;
}
/**
* Revert transformed DT_RowIndex back to its original values.
*
* @param bool $mDataSupport
*/
private function revertIndexColumn($mDataSupport): void
{
if ($this->columnDef['index']) {
$indexColumn = (string) Config::get('datatables.index_column', 'DT_RowIndex');
/** @var int|string $index */
$index = $mDataSupport ? $indexColumn : 0;
$start = $this->request->start();
$indexEdits = $mDataSupport ? $this->getIndexColumnEdits($indexColumn) : [];
$this->collection->transform(function ($data) use ($index, &$start, $mDataSupport, $indexColumn, $indexEdits) {
$data[$index] = ++$start;
if ($mDataSupport && $indexEdits !== []) {
foreach ($indexEdits as $content) {
$data[$indexColumn] = Helper::compileContent($content, $data, $data);
}
}
return $data;
});
}
}
/**
* Get edit templates/callbacks registered for the index column.
*/
private function getIndexColumnEdits(string $indexColumn): array
{
$edits = [];
foreach ($this->columnDef['edit'] ?? [] as $column) {
if (($column['name'] ?? null) === $indexColumn) {
$edits[] = $column['content'];
}
}
return $edits;
}
/**
* Define the offset of the first item of the collection with respect to
* the FULL dataset the collection was sliced from. It effectively allows the
* collection to be "pre-sliced".
*
* @return static
*/
public function setOffset(int $offset): self
{
$this->offset = $offset;
return $this;
}
/**
* Perform global search for the given keyword.
*/
protected function globalSearch(string $keyword): void
{
$keyword = $this->config->isCaseInsensitive() ? Str::lower($keyword) : $keyword;
$this->collection = $this->collection->filter(function ($row) use ($keyword) {
$data = $this->serialize($row);
foreach ($this->request->searchableColumnIndex() as $index) {
$column = $this->getColumnName($index);
$value = Arr::get($data, $column);
if (is_bool($value)) {
$value = $value ? '1' : '0';
} elseif (! is_scalar($value) && ! $value instanceof \Stringable) {
continue;
}
$value = (string) $value;
$value = $this->config->isCaseInsensitive() ? Str::lower($value) : $value;
if (Str::contains($value, $keyword)) {
return true;
}
}
return false;
});
}
/**
* Perform default query orderBy clause.
*/
protected function defaultOrdering(): void
{
$criteria = $this->request->orderableColumns();
if (! empty($criteria)) {
$sorter = $this->getSorter($criteria);
$this->collection = $this->collection
->map(fn ($data) => Arr::dot($data))
->sort($sorter)
->map(function ($data) {
foreach ($data as $key => $value) {
unset($data[$key]);
Arr::set($data, $key, $value);
}
return $data;
});
}
}
/**
* Get array sorter closure.
*/
protected function getSorter(array $criteria): Closure
{
return function ($a, $b) use ($criteria) {
foreach ($criteria as $orderable) {
$column = $this->getColumnName($orderable['column']);
$direction = $orderable['direction'];
if ($direction === 'desc') {
$first = $b;
$second = $a;
} else {
$first = $a;
$second = $b;
}
if (is_numeric($first[$column] ?? null) && is_numeric($second[$column] ?? null)) {
if ($first[$column] < $second[$column]) {
$cmp = -1;
} elseif ($first[$column] > $second[$column]) {
$cmp = 1;
} else {
$cmp = 0;
}
} elseif ($this->config->isCaseInsensitive()) {
$cmp = strnatcasecmp($first[$column] ?? '', $second[$column] ?? '');
} else {
$cmp = strnatcmp($first[$column] ?? '', $second[$column] ?? '');
}
if ($cmp != 0) {
return $cmp;
}
}
// all elements were equal
return 0;
};
}
/**
* Resolve callback parameter instance.
*
* @return array<int|string, mixed>
*/
protected function resolveCallbackParameter(): array
{
return [$this, false];
}
}
@@ -0,0 +1,59 @@
<?php
namespace Yajra\DataTables\Contracts;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
interface DataTable
{
/**
* Get results.
*
* @return \Illuminate\Support\Collection<int, \stdClass>|\Illuminate\Support\Collection<array-key, array>
*/
public function results(): Collection;
/**
* Count results.
*/
public function count(): int;
/**
* Count total items.
*/
public function totalCount(): int;
/**
* Set auto filter off and run your own filter.
* Overrides global search.
*
* @return static
*/
public function filter(callable $callback, bool $globalSearch = false): self;
/**
* Perform global search.
*/
public function filtering(): void;
/**
* Perform column search.
*/
public function columnSearch(): void;
/**
* Perform pagination.
*/
public function paging(): void;
/**
* Perform sorting of columns.
*/
public function ordering(): void;
/**
* Organizes works.
*/
public function make(bool $mDataSupport = true): JsonResponse;
}
@@ -0,0 +1,12 @@
<?php
namespace Yajra\DataTables\Contracts;
interface Formatter
{
/**
* @param array|\Illuminate\Database\Eloquent\Model|object $row
* @return string
*/
public function format(mixed $value, $row);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,162 @@
<?php
namespace Yajra\DataTables;
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Contracts\Database\Query\Builder as QueryBuilder;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Traits\Macroable;
use Yajra\DataTables\Exceptions\Exception;
use Yajra\DataTables\Utilities\Config as DataTablesConfig;
use Yajra\DataTables\Utilities\Request;
class DataTables
{
use Macroable;
/**
* DataTables request object.
*/
protected Utilities\Request $request;
/**
* Make a DataTable instance from source.
* Alias of make for backward compatibility.
*
* @param object $source
* @return DataTableAbstract
*
* @throws \Exception
*/
public static function of($source)
{
return self::make($source);
}
/**
* Make a DataTable instance from source.
*
* @param object $source
* @return DataTableAbstract
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
public static function make($source)
{
$engines = Config::get('datatables.engines', []);
$builders = Config::get('datatables.builders', []);
$args = func_get_args();
foreach ($builders as $class => $engine) {
if (is_string($class) && $source instanceof $class) {
/** @var int|string $engineKey */
$engineKey = is_int($engine) || is_string($engine) ? $engine : (string) $engine;
$callback = [$engines[$engineKey], 'create'];
if (is_callable($callback)) {
/** @var \Yajra\DataTables\DataTableAbstract $instance */
$instance = call_user_func_array($callback, $args);
return $instance;
}
}
}
foreach ($engines as $engine) {
$canCreate = [$engine, 'canCreate'];
if (is_callable($canCreate) && call_user_func_array($canCreate, $args)) {
$create = [$engine, 'create'];
if (is_callable($create)) {
/** @var \Yajra\DataTables\DataTableAbstract $instance */
$instance = call_user_func_array($create, $args);
return $instance;
}
}
}
throw new Exception('No available engine for '.$source::class);
}
/**
* Get request object.
*/
public function getRequest(): Request
{
return app('datatables.request');
}
/**
* Get config instance.
*/
public function getConfig(): DataTablesConfig
{
return app('datatables.config');
}
/**
* DataTables using query builder.
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
public function query(QueryBuilder $builder): QueryDataTable
{
$dataTable = (string) Config::get('datatables.engines.query');
$this->validateDataTable($dataTable, QueryDataTable::class);
return $dataTable::create($builder);
}
/**
* DataTables using Eloquent Builder.
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
public function eloquent(EloquentBuilder $builder): EloquentDataTable
{
$dataTable = (string) Config::get('datatables.engines.eloquent');
$this->validateDataTable($dataTable, EloquentDataTable::class);
return $dataTable::create($builder);
}
/**
* DataTables using Collection.
*
* @param \Illuminate\Support\Collection<array-key, array>|array $collection
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
public function collection($collection): CollectionDataTable
{
$dataTable = (string) Config::get('datatables.engines.collection');
$this->validateDataTable($dataTable, CollectionDataTable::class);
return $dataTable::create($collection);
}
/**
* DataTables using Collection.
*
* @param \Illuminate\Http\Resources\Json\AnonymousResourceCollection<array-key, array>|array $resource
* @return ApiResourceDataTable|DataTableAbstract
*/
public function resource($resource)
{
return ApiResourceDataTable::create($resource);
}
/**
* @throws \Yajra\DataTables\Exceptions\Exception
*/
public function validateDataTable(string $engine, string $parent): void
{
if (! ($engine == $parent || is_subclass_of($engine, $parent))) {
throw new Exception("The given datatable engine `$engine` is not compatible with `$parent`.");
}
}
}
@@ -0,0 +1,84 @@
<?php
namespace Yajra\DataTables;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Yajra\DataTables\Utilities\Config as DataTablesConfig;
use Yajra\DataTables\Utilities\Request;
class DataTablesServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
if ($this->isLumen()) {
require_once 'lumen.php';
}
$this->setupAssets();
$this->app->alias('datatables', DataTables::class);
$this->app->singleton('datatables', fn () => new DataTables);
$this->app->singleton('datatables.request', fn () => new Request);
$this->app->singleton('datatables.config', DataTablesConfig::class);
}
/**
* Boot the instance, add macros for datatable engines.
*
* @return void
*/
public function boot()
{
$engines = Config::get('datatables.engines', []);
foreach ($engines as $engine => $class) {
$engine = Str::camel($engine);
if (! method_exists(DataTables::class, $engine) && ! DataTables::hasMacro($engine)) {
DataTables::macro($engine, function () use ($class) {
$canCreate = [$class, 'canCreate'];
if (is_callable($canCreate) && ! call_user_func_array($canCreate, func_get_args())) {
throw new \InvalidArgumentException;
}
$create = [$class, 'create'];
if (is_callable($create)) {
return call_user_func_array($create, func_get_args());
}
});
}
}
}
/**
* Setup package assets.
*
* @return void
*/
protected function setupAssets()
{
$this->mergeConfigFrom($config = __DIR__.'/config/datatables.php', 'datatables');
if ($this->app->runningInConsole()) {
$this->publishes([$config => config_path('datatables.php')], 'datatables');
}
}
/**
* Check if app uses Lumen.
*
* @return bool
*/
protected function isLumen()
{
return Str::contains($this->app->version(), 'Lumen');
}
}
@@ -0,0 +1,315 @@
<?php
namespace Yajra\DataTables;
use Illuminate\Contracts\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use Yajra\DataTables\Exceptions\Exception;
/**
* @property EloquentBuilder $query
*/
class EloquentDataTable extends QueryDataTable
{
/**
* Flag to enable the generation of unique table aliases on eagerly loaded join columns.
* You may want to enable it if you encounter a "Not unique table/alias" error when performing a search or applying ordering.
*/
protected bool $enableEagerJoinAliases = false;
/**
* EloquentEngine constructor.
*/
public function __construct(Model|EloquentBuilder $model)
{
$builder = match (true) {
$model instanceof Model => $model->newQuery(),
$model instanceof Relation => $model->getQuery(),
$model instanceof EloquentBuilder => $model,
};
parent::__construct($builder->getQuery());
$this->query = $builder;
}
/**
* Can the DataTable engine be created with these parameters.
*
* @param mixed $source
*/
public static function canCreate($source): bool
{
return $source instanceof EloquentBuilder;
}
/**
* Add columns in collection.
*
* @param bool|int $order
* @return $this
*/
public function addColumns(array $names, $order = false)
{
foreach ($names as $name => $attribute) {
if (is_int($name)) {
$name = $attribute;
}
$this->addColumn($name, fn ($model) => $model->getAttribute($attribute), is_int($order) ? $order++ : $order);
}
return $this;
}
/**
* If column name could not be resolved then use primary key.
*/
protected function getPrimaryKeyName(): string
{
return $this->query->getModel()->getKeyName();
}
/**
* {@inheritDoc}
*/
protected function compileQuerySearch($query, string $column, string $keyword, string $boolean = 'or', bool $nested = false): void
{
if (substr_count($column, '.') > 1) {
$parts = explode('.', $column);
$firstRelation = array_shift($parts);
$column = implode('.', $parts);
if ($this->isMorphRelation($firstRelation)) {
$query->{$boolean.'WhereHasMorph'}(
$firstRelation,
'*',
function (EloquentBuilder $query) use ($column, $keyword) {
parent::compileQuerySearch($query, $column, $keyword, '');
}
);
} else {
$query->{$boolean.'WhereHas'}($firstRelation, function (EloquentBuilder $query) use ($column, $keyword) {
self::compileQuerySearch($query, $column, $keyword, '', true);
});
}
return;
}
$parts = explode('.', $column);
$newColumn = array_pop($parts);
$relation = implode('.', $parts);
if (! $nested && $this->isNotEagerLoaded($relation)) {
parent::compileQuerySearch($query, $column, $keyword, $boolean);
return;
}
if ($this->isMorphRelation($relation)) {
$query->{$boolean.'WhereHasMorph'}(
$relation,
'*',
function (EloquentBuilder $query) use ($newColumn, $keyword) {
parent::compileQuerySearch($query, $newColumn, $keyword, '');
}
);
} else {
$query->{$boolean.'WhereHas'}($relation, function (EloquentBuilder $query) use ($newColumn, $keyword) {
parent::compileQuerySearch($query, $newColumn, $keyword, '');
});
}
}
/**
* Check if a relation was not used on eager loading.
*
* @param string $relation
* @return bool
*/
protected function isNotEagerLoaded($relation)
{
return ! $relation
|| ! array_key_exists($relation, $this->query->getEagerLoads())
|| $relation === $this->query->getModel()->getTable();
}
/**
* Check if a relation is a morphed one or not.
*
* @param string $relation
* @return bool
*/
protected function isMorphRelation($relation)
{
$isMorph = false;
if ($relation !== null && $relation !== '') {
$relationParts = explode('.', $relation);
$firstRelation = array_shift($relationParts);
$model = $this->query->getModel();
$isMorph = method_exists($model, $firstRelation) && $model->$firstRelation() instanceof MorphTo;
}
return $isMorph;
}
/**
* {@inheritDoc}
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
protected function resolveRelationColumn(string $column): string
{
$parts = explode('.', $column);
$columnName = array_pop($parts);
$relation = preg_replace('/\[.*?\]/', '', implode('.', $parts));
if ($this->isNotEagerLoaded($relation)) {
return parent::resolveRelationColumn($column);
}
return $this->joinEagerLoadedColumn($relation, $columnName);
}
/**
* Join eager loaded relation and get the related column name.
*
* @param string $relation
* @param string $relationColumn
* @return string
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
protected function joinEagerLoadedColumn($relation, $relationColumn)
{
$tableAlias = $pivotAlias = '';
$lastQuery = $this->query;
foreach (explode('.', $relation) as $eachRelation) {
$model = $lastQuery->getRelation($eachRelation);
if ($this->enableEagerJoinAliases) {
$lastAlias = $tableAlias ?: $this->getTablePrefix($lastQuery);
$tableAlias = $tableAlias.'_'.$eachRelation;
$pivotAlias = $tableAlias.'_pivot';
} else {
$lastAlias = $tableAlias ?: $lastQuery->getModel()->getTable();
}
switch (true) {
case $model instanceof BelongsToMany:
if ($this->enableEagerJoinAliases) {
$pivot = $model->getTable().' as '.$pivotAlias;
} else {
$pivot = $pivotAlias = $model->getTable();
}
$pivotPK = $pivotAlias.'.'.$model->getForeignPivotKeyName();
$pivotFK = ltrim($lastAlias.'.'.$model->getParentKeyName(), '.');
$this->performJoin($pivot, $pivotPK, $pivotFK);
$related = $model->getRelated();
if ($this->enableEagerJoinAliases) {
$table = $related->getTable().' as '.$tableAlias;
} else {
$table = $tableAlias = $related->getTable();
}
$tablePK = $model->getRelatedPivotKeyName();
$foreign = $pivotAlias.'.'.$tablePK;
$other = $tableAlias.'.'.$related->getKeyName();
$lastQuery->addSelect($tableAlias.'.'.$relationColumn);
break;
case $model instanceof HasOneThrough:
if ($this->enableEagerJoinAliases) {
$pivot = explode('.', $model->getQualifiedParentKeyName())[0].' as '.$pivotAlias;
} else {
$pivot = $pivotAlias = explode('.', $model->getQualifiedParentKeyName())[0];
}
$pivotPK = $pivotAlias.'.'.$model->getFirstKeyName();
$pivotFK = ltrim($lastAlias.'.'.$model->getLocalKeyName(), '.');
$this->performJoin($pivot, $pivotPK, $pivotFK);
$related = $model->getRelated();
if ($this->enableEagerJoinAliases) {
$table = $related->getTable().' as '.$tableAlias;
} else {
$table = $tableAlias = $related->getTable();
}
$tablePK = $model->getSecondLocalKeyName();
$foreign = $pivotAlias.'.'.$tablePK;
$other = $tableAlias.'.'.$related->getKeyName();
$lastQuery->addSelect($lastQuery->getModel()->getTable().'.*');
break;
case $model instanceof HasOneOrMany:
if ($this->enableEagerJoinAliases) {
$table = $model->getRelated()->getTable().' as '.$tableAlias;
} else {
$table = $tableAlias = $model->getRelated()->getTable();
}
$foreign = $tableAlias.'.'.$model->getForeignKeyName();
$other = ltrim($lastAlias.'.'.$model->getLocalKeyName(), '.');
break;
case $model instanceof BelongsTo:
if ($this->enableEagerJoinAliases) {
$table = $model->getRelated()->getTable().' as '.$tableAlias;
} else {
$table = $tableAlias = $model->getRelated()->getTable();
}
$foreign = ltrim($lastAlias.'.'.$model->getForeignKeyName(), '.');
$other = $tableAlias.'.'.$model->getOwnerKeyName();
break;
default:
throw new Exception('Relation '.$model::class.' is not yet supported.');
}
$this->performJoin($table, $foreign, $other);
$lastQuery = $model->getQuery();
}
return $tableAlias.'.'.$relationColumn;
}
/**
* Enable the generation of unique table aliases on eagerly loaded join columns.
* You may want to enable it if you encounter a "Not unique table/alias" error when performing a search or applying ordering.
*
* @return $this
*/
public function enableEagerJoinAliases(): static
{
$this->enableEagerJoinAliases = true;
return $this;
}
/**
* Perform join query.
*
* @param string $table
* @param string $foreign
* @param string $other
* @param string $type
*/
protected function performJoin($table, $foreign, $other, $type = 'left'): void
{
$joins = [];
$builder = $this->getBaseQueryBuilder();
foreach ($builder->joins ?? [] as $join) {
$joins[] = $join->table;
}
if (! in_array($table, $joins)) {
$this->getBaseQueryBuilder()->join($table, $foreign, '=', $other, $type);
}
}
}
@@ -0,0 +1,5 @@
<?php
namespace Yajra\DataTables\Exceptions;
class Exception extends \Exception {}
@@ -0,0 +1,27 @@
<?php
namespace Yajra\DataTables\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @mixin \Yajra\DataTables\DataTables
*
* @method static \Yajra\DataTables\EloquentDataTable eloquent($builder)
* @method static \Yajra\DataTables\QueryDataTable query($builder)
* @method static \Yajra\DataTables\CollectionDataTable collection($collection)
*
* @see \Yajra\DataTables\DataTables
*/
class DataTables extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'datatables';
}
}
@@ -0,0 +1,44 @@
<?php
namespace Yajra\DataTables;
use Illuminate\Pagination\LengthAwarePaginator;
class PaginatorDataTable extends CollectionDataTable
{
/**
* @param LengthAwarePaginator<int, mixed> $paginator
*/
public function __construct(protected LengthAwarePaginator $paginator)
{
parent::__construct(collect($paginator->items()));
$this->skipPaging();
}
/**
* Can the DataTable engine be created with these parameters.
*
* @param mixed $source
*/
public static function canCreate($source): bool
{
return $source instanceof LengthAwarePaginator;
}
/**
* Count total items from paginator.
*/
public function totalCount(): int
{
return $this->totalRecords ??= $this->paginator->total();
}
/**
* Skip datatable-side filtering since the source is pre-paginated.
*/
protected function filterRecords(): void
{
$this->filteredRecords = $this->totalCount();
}
}
@@ -0,0 +1,263 @@
<?php
namespace Yajra\DataTables\Processors;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Yajra\DataTables\Contracts\Formatter;
use Yajra\DataTables\Utilities\Helper;
class DataProcessor
{
protected array $output = [];
/**
* @var array<array-key, array{name: string, content: mixed}>
*/
protected array $appendColumns = [];
/**
* @var array<array-key, array{name: string, content: mixed}>
*/
protected array $editColumns = [];
protected array $rawColumns = [];
/**
* @var array|string[]
*/
protected array $exceptions = ['DT_RowId', 'DT_RowClass', 'DT_RowData', 'DT_RowAttr'];
protected array $onlyColumns = [];
protected array $makeHidden = [];
protected array $makeVisible = [];
protected array $excessColumns = [];
/**
* @var string|array
*/
protected mixed $escapeColumns = [];
protected bool $includeIndex = false;
protected bool $ignoreGetters = false;
protected string $indexColumn;
public function __construct(protected iterable $results, array $columnDef, protected array $templates, protected int $start = 0)
{
$this->appendColumns = $columnDef['append'] ?? [];
$this->editColumns = $columnDef['edit'] ?? [];
$this->excessColumns = $columnDef['excess'] ?? [];
$this->onlyColumns = $columnDef['only'] ?? [];
$this->escapeColumns = $columnDef['escape'] ?? [];
$this->includeIndex = $columnDef['index'] ?? false;
$this->rawColumns = $columnDef['raw'] ?? [];
$this->makeHidden = $columnDef['hidden'] ?? [];
$this->makeVisible = $columnDef['visible'] ?? [];
$this->ignoreGetters = $columnDef['ignore_getters'] ?? false;
$this->indexColumn = (string) Config::get('datatables.index_column', 'DT_RowIndex');
}
/**
* Process data to output on browser.
*
* @param bool $object
*/
public function process($object = false): array
{
$this->output = [];
foreach ($this->results as $row) {
$data = Helper::convertToArray($row, ['hidden' => $this->makeHidden, 'visible' => $this->makeVisible, 'ignore_getters' => $this->ignoreGetters]);
$value = $this->addColumns($data, $row);
$value = $this->editColumns($value, $row);
$value = $this->setupRowVariables($value, $row);
$value = $this->selectOnlyNeededColumns($value);
$value = $this->removeExcessColumns($value);
if ($this->includeIndex) {
$value[$this->indexColumn] = ++$this->start;
$value = $this->editIndexColumn($value, $row);
}
$this->output[] = $object ? $value : $this->flatten($value);
}
return $this->escapeColumns($this->output);
}
/**
* Process add columns.
*
* @param array|object|\Illuminate\Database\Eloquent\Model $row
*/
protected function addColumns(array $data, $row): array
{
foreach ($this->appendColumns as $value) {
$content = $value['content'];
if ($content instanceof Formatter) {
$column = str_replace('_formatted', '', $value['name']);
$value['content'] = $content->format($data[$column], $row);
if (isset($data[$column])) {
$value['content'] = $content->format($data[$column], $row);
}
} else {
$value['content'] = Helper::compileContent($content, $data, $row);
}
$data = Helper::includeInArray($value, $data);
}
return $data;
}
/**
* Process edit columns.
*/
protected function editColumns(array $data, object|array $row): array
{
foreach ($this->editColumns as $value) {
if ($this->includeIndex && $value['name'] === $this->indexColumn) {
continue;
}
$value['content'] = Helper::compileContent($value['content'], $data, $row);
Arr::set($data, $value['name'], $value['content']);
}
return $data;
}
/**
* Edit index column after it has been added to the row.
*/
protected function editIndexColumn(array $data, object|array $row): array
{
if (! $this->includeIndex) {
return $data;
}
foreach ($this->editColumns as $value) {
if ($value['name'] !== $this->indexColumn) {
continue;
}
$value['content'] = Helper::compileContent($value['content'], $data, $row);
Arr::set($data, $this->indexColumn, $value['content']);
}
return $data;
}
/**
* Setup additional DT row variables.
*/
protected function setupRowVariables(array $data, object|array $row): array
{
$processor = new RowProcessor($data, $row);
return $processor
->rowValue('DT_RowId', $this->templates['DT_RowId'])
->rowValue('DT_RowClass', $this->templates['DT_RowClass'])
->rowData('DT_RowData', $this->templates['DT_RowData'])
->rowData('DT_RowAttr', $this->templates['DT_RowAttr'])
->getData();
}
/**
* Get only needed columns.
*/
protected function selectOnlyNeededColumns(array $data): array
{
if (empty($this->onlyColumns)) {
return $data;
} else {
$results = [];
foreach ($this->onlyColumns as $onlyColumn) {
Arr::set($results, $onlyColumn, Arr::get($data, $onlyColumn));
}
foreach ($this->exceptions as $exception) {
if ($column = Arr::get($data, $exception)) {
Arr::set($results, $exception, $column);
}
}
return $results;
}
}
/**
* Remove declared hidden columns.
*/
protected function removeExcessColumns(array $data): array
{
foreach ($this->excessColumns as $value) {
Arr::forget($data, $value);
}
return $data;
}
/**
* Flatten array with exceptions.
*/
public function flatten(array $array): array
{
$return = [];
foreach ($array as $key => $value) {
if (in_array($key, $this->exceptions)) {
$return[$key] = $value;
} else {
$return[] = $value;
}
}
return $return;
}
/**
* Escape column values as declared.
*/
protected function escapeColumns(array $output): array
{
return array_map(function ($row) {
if ($this->escapeColumns == '*') {
$row = $this->escapeRow($row);
} elseif (is_array($this->escapeColumns)) {
$columns = array_diff($this->escapeColumns, $this->rawColumns);
foreach ($columns as $key) {
/** @var string $content */
$content = Arr::get($row, $key);
Arr::set($row, $key, e($content));
}
}
return $row;
}, $output);
}
/**
* Escape all string or Htmlable values of row.
*/
protected function escapeRow(array $row): array
{
$arrayDot = array_filter(Arr::dot($row));
foreach ($arrayDot as $key => $value) {
if (! in_array($key, $this->rawColumns)) {
$arrayDot[$key] = (is_string($value) || $value instanceof Htmlable) ? e($value) : $value;
}
}
foreach ($arrayDot as $key => $value) {
Arr::set($row, $key, $value);
}
return $row;
}
}
@@ -0,0 +1,64 @@
<?php
namespace Yajra\DataTables\Processors;
use Illuminate\Support\Arr;
use Yajra\DataTables\Utilities\Helper;
class RowProcessor
{
/**
* @param array|object $row
*/
public function __construct(protected array $data, protected $row) {}
/**
* Process DT RowId and Class value.
*
* @param string $attribute
* @param string|callable $template
* @return $this
*
* @throws \ReflectionException
*/
public function rowValue($attribute, $template)
{
if (! empty($template)) {
if (! is_callable($template) && Arr::get($this->data, $template)) {
$this->data[$attribute] = Arr::get($this->data, $template);
} else {
$this->data[$attribute] = Helper::compileContent($template, $this->data, $this->row);
}
}
return $this;
}
/**
* Process DT Row Data and Attr.
*
* @param string $attribute
* @return $this
*
* @throws \ReflectionException
*/
public function rowData($attribute, array $template)
{
if (count($template)) {
$this->data[$attribute] = [];
foreach ($template as $key => $value) {
$this->data[$attribute][$key] = Helper::compileContent($value, $this->data, $this->row);
}
}
return $this;
}
/**
* @return array
*/
public function getData()
{
return $this->data;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,96 @@
<?php
namespace Yajra\DataTables\Utilities;
use Illuminate\Contracts\Config\Repository;
class Config
{
/**
* Config constructor.
*/
public function __construct(private readonly Repository $repository) {}
/**
* Check if config uses wild card search.
*/
public function isWildcard(): bool
{
return (bool) $this->repository->get('datatables.search.use_wildcards', false);
}
/**
* Check if config uses smart search.
*/
public function isSmartSearch(): bool
{
return (bool) $this->repository->get('datatables.search.smart', true);
}
/**
* Check if config uses case-insensitive search.
*/
public function isCaseInsensitive(): bool
{
return (bool) $this->repository->get('datatables.search.case_insensitive', false);
}
/**
* Check if app is in debug mode.
*/
public function isDebugging(): bool
{
return (bool) $this->repository->get('app.debug', false);
}
/**
* Get the specified configuration value.
*
* @param string $key
* @return mixed
*/
public function get($key, mixed $default = null)
{
return $this->repository->get($key, $default);
}
/**
* Set a given configuration value.
*
* @param array|string $key
* @return void
*/
public function set($key, mixed $value = null)
{
$this->repository->set($key, $value);
}
/**
* Check if dataTable config uses multi-term searching.
*/
public function isMultiTerm(): bool
{
return (bool) $this->repository->get('datatables.search.multi_term', true);
}
/**
* Check if dataTable config uses starts_with searching.
*/
public function isStartsWithSearch(): bool
{
return (bool) $this->repository->get('datatables.search.starts_with', false);
}
public function jsonOptions(): int
{
/** @var int $options */
$options = $this->repository->get('datatables.json.options', 0);
return $options;
}
public function jsonHeaders(): array
{
return (array) $this->repository->get('datatables.json.header', []);
}
}
@@ -0,0 +1,369 @@
<?php
namespace Yajra\DataTables\Utilities;
use Closure;
use DateTime;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use ReflectionFunction;
use ReflectionMethod;
class Helper
{
/**
* Places item of extra columns into results by care of their order.
*/
public static function includeInArray(array $item, array $array): array
{
/** @var int|string $itemName */
$itemName = is_int($item['name']) || is_string($item['name']) ? $item['name'] : (string) $item['name'];
if (self::isItemOrderInvalid($item, $array)) {
return array_merge($array, [$itemName => $item['content']]);
}
$count = 0;
$last = $array;
$first = [];
foreach ($array as $key => $value) {
if ($count == $item['order']) {
continue;
}
unset($last[$key]);
$first[$key] = $value;
$count++;
}
return array_merge($first, [$itemName => $item['content']], $last);
}
/**
* Check if item order is valid.
*/
protected static function isItemOrderInvalid(array $item, array $array): bool
{
return $item['order'] === false || $item['order'] >= count($array);
}
/**
* Gets the parameter of a callable thing (from is_callable) and returns it's arguments using reflection.
*
* @param callable $callable
* @return \ReflectionParameter[]
*
* @throws \ReflectionException
* @throws \InvalidArgumentException
*/
private static function reflectCallableParameters($callable)
{
/*
loosely after https://github.com/technically-php/callable-reflection/blob/main/src/CallableReflection.php#L72-L86.
Licence is compatible, both project use MIT
*/
if ($callable instanceof Closure) {
$reflection = new ReflectionFunction($callable);
} elseif (is_string($callable) && function_exists($callable)) {
$reflection = new ReflectionFunction($callable);
} elseif (is_string($callable) && str_contains($callable, '::')) {
$reflection = new ReflectionMethod($callable);
} elseif (is_object($callable) && method_exists($callable, '__invoke')) {
$reflection = new ReflectionMethod($callable, '__invoke');
} else {
throw new \InvalidArgumentException('argument is not callable or the code is wrong');
}
return $reflection->getParameters();
}
/**
* Determines if content is callable or blade string, processes and returns.
*
* @param mixed $content Pre-processed content
* @param array $data data to use with blade template
* @param array|object $param parameter to call with callable
* @return mixed
*
* @throws \ReflectionException
*/
public static function compileContent(mixed $content, array $data, array|object $param)
{
if (is_string($content)) {
return static::compileBlade($content, static::getMixedValue($data, $param));
}
if (is_callable($content)) {
$arguments = self::reflectCallableParameters($content);
if (count($arguments) > 0) {
return app()->call($content, [$arguments[0]->name => $param]);
}
return $content($param);
}
if (is_array($content)) {
[$view, $viewData] = $content;
return static::compileBlade($view, static::getMixedValue($data, $param) + $viewData);
}
return $content;
}
/**
* Parses and compiles strings by using Blade Template System.
*
*
* @throws \Throwable
*/
public static function compileBlade(string $str, array $data = []): false|string
{
if (view()->exists($str)) {
/** @var view-string $str */
return view($str, $data)->render();
}
return Blade::render($str, $data);
}
/**
* Get a mixed value of custom data and the parameters.
*/
public static function getMixedValue(array $data, array|object $param): array
{
$casted = self::castToArray($param);
$data['model'] = $param;
foreach ($data as $key => $value) {
if (isset($casted[$key])) {
$data[$key] = $casted[$key];
}
}
return $data;
}
/**
* Cast the parameter into an array.
*/
public static function castToArray(array|object $param): array
{
if ($param instanceof Arrayable) {
return $param->toArray();
}
return (array) $param;
}
/**
* Get equivalent or method of query builder.
*/
public static function getOrMethod(string $method): string
{
if (! Str::contains(Str::lower($method), 'or')) {
return 'or'.ucfirst($method);
}
return $method;
}
/**
* Converts array object values to associative array.
*/
public static function convertToArray(mixed $row, array $filters = []): array
{
if (Arr::get($filters, 'ignore_getters') && is_object($row) && method_exists($row, 'getAttributes')) {
$data = $row->getAttributes();
if (method_exists($row, 'getRelations')) {
foreach ($row->getRelations() as $relationName => $relation) {
if (is_iterable($relation)) {
foreach ($relation as $relationItem) {
$data[$relationName][] = self::convertToArray($relationItem, ['ignore_getters' => true]);
}
} else {
$data[$relationName] = self::convertToArray($relation, ['ignore_getters' => true]);
}
}
}
return $data;
}
$row = is_object($row) && method_exists($row, 'makeHidden') ? $row->makeHidden(Arr::get($filters, 'hidden',
[])) : $row;
$row = is_object($row) && method_exists($row, 'makeVisible') ? $row->makeVisible(Arr::get($filters, 'visible',
[])) : $row;
$data = $row instanceof Arrayable ? $row->toArray() : (array) $row;
foreach ($data as &$value) {
if ((is_object($value) && ! $value instanceof DateTime) || is_array($value)) {
$value = self::convertToArray($value);
}
unset($value);
}
return $data;
}
public static function transform(array $data): array
{
return array_map(fn ($row) => self::transformRow($row), $data);
}
/**
* Transform row data into an array.
*
* @param array $row
*/
protected static function transformRow($row): array
{
foreach ($row as $key => $value) {
if ($value instanceof DateTime) {
$row[$key] = $value->format('Y-m-d H:i:s');
} else {
if (is_object($value) && method_exists($value, '__toString')) {
$row[$key] = $value->__toString();
} else {
$row[$key] = $value;
}
}
}
return $row;
}
/**
* Build parameters depending on # of arguments passed.
*/
public static function buildParameters(array $args): array
{
$parameters = [];
if (count($args) > 2) {
$parameters[] = $args[0];
foreach ($args[1] as $param) {
$parameters[] = $param;
}
} else {
foreach ($args[0] as $param) {
$parameters[] = $param;
}
}
return $parameters;
}
/**
* Replace all pattern occurrences with keyword.
*/
public static function replacePatternWithKeyword(array $subject, string $keyword, string $pattern = '$1'): array
{
$parameters = [];
foreach ($subject as $param) {
if (is_array($param)) {
$parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern);
} else {
$parameters[] = str_replace($pattern, $keyword, (string) $param);
}
}
return $parameters;
}
/**
* Get column name from string.
*/
public static function extractColumnName(string $str, bool $wantsAlias): string
{
$matches = explode(' as ', Str::lower($str));
if (count($matches) > 1) {
if ($wantsAlias) {
return array_pop($matches);
}
return array_shift($matches);
} elseif (strpos($str, '.')) {
$array = explode('.', $str);
return array_pop($array);
}
return $str;
}
/**
* Adds % wildcards to the given string.
*/
public static function wildcardLikeString(string $str, bool $lowercase = true): string
{
return static::wildcardString($str, '%', $lowercase);
}
/**
* Adds wildcards to the given string.
*/
public static function wildcardString(string $str, string $wildcard, bool $lowercase = true): string
{
$wild = $wildcard;
$chars = (array) preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
if (count($chars) > 0) {
foreach ($chars as $char) {
$wild .= $char.$wildcard;
}
}
if ($lowercase) {
$wild = Str::lower($wild);
}
return $wild;
}
public static function toJsonScript(array $parameters, int $options = 0): string
{
$values = [];
$replacements = [];
foreach (Arr::dot($parameters) as $key => $value) {
if (self::isJavascript($value, $key)) {
$values[] = trim((string) $value);
Arr::set($parameters, $key, '%'.$key.'%');
$replacements[] = '"%'.$key.'%"';
}
}
$new = [];
foreach ($parameters as $key => $value) {
Arr::set($new, $key, $value);
}
$json = (string) json_encode($new, $options);
return str_replace($replacements, $values, $json);
}
public static function isJavascript(string|array|object|null $value, string $key): bool
{
if (empty($value) || is_array($value) || is_object($value)) {
return false;
}
$callbacks = Config::get('datatables.callback', ['$', '$.', 'function']);
if (Str::startsWith($key, 'language.')) {
return false;
}
return Str::startsWith(trim($value), $callbacks) || Str::contains($key, ['editor', 'minDate', 'maxDate']);
}
}
@@ -0,0 +1,252 @@
<?php
namespace Yajra\DataTables\Utilities;
use Illuminate\Http\Request as BaseRequest;
/**
* @mixin \Illuminate\Http\Request
*/
class Request
{
/**
* Proxy non-existing method calls to base request class.
*
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
$callback = [request(), $name];
if (is_callable($callback)) {
return call_user_func_array($callback, $arguments);
}
}
/**
* Determine if an attribute exists on the base request.
*
* @param string $name
*/
public function __isset($name): bool
{
return isset(request()->$name);
}
/**
* Get attributes from request instance.
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
return request()->__get($name);
}
/**
* Get all columns request input.
*/
public function columns(): array
{
return (array) request()->input('columns');
}
/**
* Check if DataTables is searchable.
*/
public function isSearchable(): bool
{
return request()->input('search.value') != '';
}
/**
* Check if DataTables must uses regular expressions.
*/
public function isRegex(int $index): bool
{
return request()->input("columns.$index.search.regex") === 'true';
}
/**
* Get orderable columns.
*/
public function orderableColumns(): array
{
if (! $this->isOrderable()) {
return [];
}
$orderable = [];
for ($i = 0, $c = count((array) request()->input('order')); $i < $c; $i++) {
/** @var int $order_col */
$order_col = request()->input("order.$i.column");
/** @var string $direction */
$direction = request()->input("order.$i.dir");
$order_dir = $direction && strtolower($direction) === 'asc' ? 'asc' : 'desc';
if ($this->isColumnOrderable($order_col)) {
$orderable[] = ['column' => $order_col, 'direction' => $order_dir];
}
}
return $orderable;
}
/**
* Check if DataTables ordering is enabled.
*/
public function isOrderable(): bool
{
return request()->input('order') && count((array) request()->input('order')) > 0;
}
/**
* Check if a column is orderable.
*/
public function isColumnOrderable(int $index): bool
{
return request()->input("columns.$index.orderable", 'true') == 'true';
}
/**
* Get searchable column indexes.
*
* @return array
*/
public function searchableColumnIndex()
{
$searchable = [];
$columns = (array) request()->input('columns');
for ($i = 0, $c = count($columns); $i < $c; $i++) {
if ($this->isColumnSearchable($i, false)) {
$searchable[] = $i;
}
}
return $searchable;
}
/**
* Check if a column is searchable.
*/
public function isColumnSearchable(int $i, bool $column_search = true): bool
{
if ($column_search) {
return
(
request()->input("columns.$i.searchable", 'true') === 'true'
||
request()->input("columns.$i.searchable", 'true') === true
)
&& $this->columnKeyword($i) != '';
}
return
request()->input("columns.$i.searchable", 'true') === 'true'
||
request()->input("columns.$i.searchable", 'true') === true;
}
/**
* Get column's search value.
*/
public function columnKeyword(int $index): string
{
/** @var string $keyword */
$keyword = request()->input("columns.$index.search.value") ?? '';
return $this->prepareKeyword($keyword);
}
public function columnControl(int $index): array
{
return request()->array("columns.$index.columnControl");
}
public function columnControlSearch(int $index): array
{
return request()->array("columns.$index.columnControl.search");
}
/**
* Prepare keyword string value.
*/
protected function prepareKeyword(float|array|int|string $keyword): string
{
if (is_array($keyword)) {
return implode(' ', $keyword);
}
return (string) $keyword;
}
/**
* Get global search keyword.
*/
public function keyword(): string
{
/** @var string $keyword */
$keyword = request()->input('search.value') ?? '';
return $this->prepareKeyword($keyword);
}
/**
* Get column name by index.
*/
public function columnName(int $i): ?string
{
/** @var string[] $column */
$column = request()->input("columns.$i");
return (isset($column['name']) && $column['name'] != '') ? $column['name'] : $column['data'];
}
/**
* Check if DataTables allow pagination.
*/
public function isPaginationable(): bool
{
return ! is_null(request()->input('start')) &&
! is_null(request()->input('length')) &&
request()->input('length') != -1;
}
public function getBaseRequest(): BaseRequest
{
return request();
}
/**
* Get starting record value.
*/
public function start(): int
{
$start = request()->input('start', 0);
return is_numeric($start) ? intval($start) : 0;
}
/**
* Get per page length.
*/
public function length(): int
{
$length = request()->input('length', 10);
return is_numeric($length) ? intval($length) : 10;
}
/**
* Get draw request.
*/
public function draw(): int
{
$draw = request()->input('draw', 0);
return is_numeric($draw) ? intval($draw) : 0;
}
}
@@ -0,0 +1,129 @@
<?php
return [
/*
* DataTables search options.
*/
'search' => [
/*
* Smart search will enclose search keyword with wildcard string "%keyword%".
* SQL: column LIKE "%keyword%"
*/
'smart' => true,
/*
* Multi-term search will explode search keyword using spaces resulting into multiple term search.
*/
'multi_term' => true,
/*
* Case insensitive will search the keyword in lower case format.
* SQL: LOWER(column) LIKE LOWER(keyword)
*/
'case_insensitive' => true,
/*
* Wild card will add "%" in between every characters of the keyword.
* SQL: column LIKE "%k%e%y%w%o%r%d%"
*/
'use_wildcards' => false,
/*
* Perform a search which starts with the given keyword.
* SQL: column LIKE "keyword%"
*/
'starts_with' => false,
],
/*
* DataTables internal index id response column name.
*/
'index_column' => 'DT_RowIndex',
/*
* List of available builders for DataTables.
* This is where you can register your custom DataTables builder.
*/
'engines' => [
'eloquent' => Yajra\DataTables\EloquentDataTable::class,
'query' => Yajra\DataTables\QueryDataTable::class,
'collection' => Yajra\DataTables\CollectionDataTable::class,
'paginator' => Yajra\DataTables\PaginatorDataTable::class,
'resource' => Yajra\DataTables\ApiResourceDataTable::class,
],
/*
* DataTables accepted builder to engine mapping.
* This is where you can override which engine a builder should use
* Note, only change this if you know what you are doing!
*/
'builders' => [
// Illuminate\Database\Eloquent\Relations\Relation::class => 'eloquent',
// Illuminate\Database\Eloquent\Builder::class => 'eloquent',
// Illuminate\Database\Query\Builder::class => 'query',
// Illuminate\Support\Collection::class => 'collection',
// Illuminate\Pagination\LengthAwarePaginator::class => 'paginator',
],
/*
* Nulls last sql pattern for PostgreSQL & Oracle.
* For MySQL, use 'CASE WHEN :column IS NULL THEN 1 ELSE 0 END, :column :direction'
*/
'nulls_last_sql' => ':column :direction NULLS LAST',
/*
* User friendly message to be displayed on user if error occurs.
* Possible values:
* null - The exception message will be used on error response.
* 'throw' - Throws a \Yajra\DataTables\Exceptions\Exception. Use your custom error handler if needed.
* 'custom message' - Any friendly message to be displayed to the user. You can also use translation key.
*/
'error' => env('DATATABLES_ERROR', null),
/*
* Default columns definition of DataTable utility functions.
*/
'columns' => [
/*
* List of columns hidden/removed on json response.
*/
'excess' => ['rn', 'row_num'],
/*
* List of columns to be escaped. If set to *, all columns are escape.
* Note: You can set the value to empty array to disable XSS protection.
*/
'escape' => '*',
/*
* List of columns that are allowed to display html content.
* Note: Adding columns to list will make us available to XSS attacks.
*/
'raw' => ['action'],
/*
* List of columns are forbidden from being searched/sorted.
*/
'blacklist' => ['password', 'remember_token'],
/*
* List of columns that are only allowed for search/sort.
* If set to *, all columns are allowed.
*/
'whitelist' => '*',
],
/*
* JsonResponse header and options config.
*/
'json' => [
'header' => [],
'options' => 0,
],
/*
* Default condition to determine if a parameter is a callback or not.
* Callbacks needs to start by those terms, or they will be cast to string.
*/
'callback' => ['$', '$.', 'function'],
];
+24
View File
@@ -0,0 +1,24 @@
<?php
if (! function_exists('datatables')) {
/**
* Helper to make a new DataTable instance from source.
* Or return the factory if source is not set.
*
* @param \Illuminate\Contracts\Database\Query\Builder|\Illuminate\Contracts\Database\Eloquent\Builder|\Illuminate\Support\Collection|array|null $source
* @return ($source is null ? \Yajra\DataTables\DataTables : \Yajra\DataTables\DataTableAbstract)
*
* @throws \Yajra\DataTables\Exceptions\Exception
*/
function datatables($source = null)
{
/** @var Yajra\DataTables\DataTables $dataTable */
$dataTable = app('datatables');
if (is_null($source)) {
return $dataTable;
}
return $dataTable->make($source);
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
if (! function_exists('config_path')) {
/**
* Get the configuration path.
*
* @param string $path
* @return string
*/
function config_path($path = '')
{
return app()->basePath().'/config'.($path ? '/'.$path : $path);
}
}
if (! function_exists('public_path')) {
/**
* Return the path to public dir.
*
* @param null $path
* @return string
*/
function public_path($path = null)
{
return rtrim((string) app()->basePath('public/'.$path), '/');
}
}