Skip to content

Commit

Permalink
fix route model binding attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
d8vjork committed Sep 27, 2023
1 parent e72a054 commit 0c4e243
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/PropertiesMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -121,13 +123,15 @@ public function get(): array
*/
protected function getModelInstance(string $model, mixed $id, string $usingAttribute = null, array $with = [])
{
$usingAttribute ??= (new $model)->getRouteKeyName();

if (is_a($id, $model)) {
return empty($with) ? $id : $id->loadMissing($with);
}

$baseQuery = $model::query()->whereKey($id);
$baseQuery = $model::query()->when(
$usingAttribute,
fn (Builder $query) => $query->where($usingAttribute, $id),
fn (Builder $query) => $query->whereKey($id)
);

if (count($with) > 0) {
$baseQuery->with($with);
Expand Down Expand Up @@ -180,10 +184,16 @@ protected function mapIntoModel(string $modelClass, string $propertyKey, mixed $
/** @var \ReflectionAttribute<\OpenSoutheners\LaravelDto\Attributes\BindModelUsing>|null $bindModelUsingAttribute */
$bindModelUsingAttribute = reset($bindModelUsingAttribute);

$bindModelUsingAttribute = $bindModelUsingAttribute ? $bindModelUsingAttribute->newInstance()->attribute : null;

if (! $bindModelUsingAttribute && app(Request::class)->route($propertyKey)) {
$bindModelUsingAttribute = app(Request::class)->route()->bindingFieldFor($propertyKey) ?? (new $modelClass)->getRouteKeyName();
}

return $this->getModelInstance(
$modelClass,
$value,
$bindModelUsingAttribute ? $bindModelUsingAttribute->newInstance()->attribute : null,
$bindModelUsingAttribute,
$bindModelWithAttribute
? (array) $bindModelWithAttribute->newInstance()->relationships
: []
Expand Down

0 comments on commit 0c4e243

Please sign in to comment.