Skip to content

Commit

Permalink
Merge pull request #2789 from sebdesign/eloquent-relation
Browse files Browse the repository at this point in the history
Create eloquent datatable from relation
  • Loading branch information
yajra authored May 23, 2022
2 parents 85a1186 + 97c3bd9 commit 24e71b5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
29 changes: 13 additions & 16 deletions src/EloquentDataTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
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;

/**
Expand All @@ -19,22 +20,15 @@ class EloquentDataTable extends QueryDataTable
/**
* EloquentEngine constructor.
*
* @param \Illuminate\Database\Eloquent\Model|EloquentBuilder $model
*
* @throws \Yajra\DataTables\Exceptions\Exception
* @param Model|EloquentBuilder $model
*/
public function __construct($model)
public function __construct(Model|EloquentBuilder $model)
{
switch ($model) {
case $model instanceof Model:
$builder = $model->newQuery();
break;
case $model instanceof EloquentBuilder:
$builder = $model;
break;
default:
throw new Exception('Invalid model type. Must be an instance of Eloquent Model or Eloquent Builder.');
}
$builder = match (true) {
$model instanceof Model => $model->newQuery(),
$model instanceof Relation => $model->getQuery(),
$model instanceof EloquentBuilder => $model,
};

parent::__construct($builder->getQuery());

Expand Down Expand Up @@ -100,10 +94,13 @@ protected function compileQuerySearch($query, string $column, string $keyword, s
}

if ($this->isMorphRelation($relation)) {
$query->{$boolean.'WhereHasMorph'}($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, '');
Expand Down
11 changes: 11 additions & 0 deletions tests/Integration/EloquentDataTableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,17 @@ public function it_can_return_formatted_columns()
$this->assertEquals(Carbon::parse($user->created_at)->format('Y-m-d'), $data['created_at_formatted']);
}

/** @test */
public function it_accepts_a_relation()
{
$user = User::first();

$dataTable = app('datatables')->eloquent($user->posts());
$response = $dataTable->toJson();
$this->assertInstanceOf(EloquentDataTable::class, $dataTable);
$this->assertInstanceOf(JsonResponse::class, $response);
}

protected function setUp(): void
{
parent::setUp();
Expand Down

0 comments on commit 24e71b5

Please sign in to comment.