Skip to content

Commit

Permalink
add fallback locale support and additional query support to `HasSlug@…
Browse files Browse the repository at this point in the history
…findBySlug` method
  • Loading branch information
mkeremcansev committed Dec 3, 2024
1 parent ed4a927 commit 35d314a
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/HasSlug.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,15 +190,31 @@ protected function generateSubstring($slugSourceString)
return substr($slugSourceString, 0, $this->slugOptions->maximumLength);
}

public static function findBySlug(string $slug, array $columns = ['*'])
public static function findBySlug(string $slug, array $columns = ['*'], callable $additionalQuery = null)
{
$modelInstance = new static();
$field = $modelInstance->getSlugOptions()->slugField;

$field = in_array(HasTranslatableSlug::class, class_uses_recursive(static::class))
? "{$field}->{$modelInstance->getLocale()}"
: $field;
$currentLocale = $modelInstance->getLocale();
$fallbackLocale = config('app.fallback_locale');

return static::where($field, $slug)->first($columns);
$query = static::query();

if (in_array(HasTranslatableSlug::class, class_uses_recursive(static::class))) {
$currentField = "{$field}->{$currentLocale}";
$fallbackField = "{$field}->{$fallbackLocale}";

$query->where($currentField, $slug);

$query->orWhere($fallbackField, $slug);
} else {
$query->where($field, $slug);
}

if (is_callable($additionalQuery)) {
$additionalQuery($query);
}

return $query->first($columns);
}
}

0 comments on commit 35d314a

Please sign in to comment.