From ac56889a8742d004958f08f15f50f33c4c16367d Mon Sep 17 00:00:00 2001 From: Yutaka Kurosaki Date: Sat, 29 Nov 2025 17:22:17 +0900 Subject: [PATCH] fix: Use slug for Document route model binding - Add getRouteKeyName() to return 'slug' for Document model - Add resolveRouteBinding() to support both slug and ID lookups - Update QuickSwitcher to use slug instead of ID - Update quick-switcher blade to use slug in routes This ensures URLs use readable slugs (e.g., /documents/home) while maintaining backwards compatibility with ID-based URLs --- src/app/Livewire/QuickSwitcher.php | 6 ++-- src/app/Models/Document.php | 31 +++++++++++++++++++ .../views/livewire/quick-switcher.blade.php | 2 +- 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/app/Livewire/QuickSwitcher.php b/src/app/Livewire/QuickSwitcher.php index 955b52e..e51b6cf 100644 --- a/src/app/Livewire/QuickSwitcher.php +++ b/src/app/Livewire/QuickSwitcher.php @@ -93,9 +93,9 @@ public function selectDocument() if (isset($results[$this->selectedIndex])) { $document = $results[$this->selectedIndex]; - // id が存在することを確認 - if (!empty($document['id'])) { - return $this->redirect(route('documents.show', $document['id'])); + // slug が存在することを確認 + if (!empty($document['slug'])) { + return $this->redirect(route('documents.show', $document['slug'])); } } } diff --git a/src/app/Models/Document.php b/src/app/Models/Document.php index 44495ea..bdfb981 100644 --- a/src/app/Models/Document.php +++ b/src/app/Models/Document.php @@ -19,6 +19,37 @@ class Document extends Model { use SoftDeletes; + /** + * Get the route key for the model. + * + * @return string + */ + public function getRouteKeyName(): string + { + return 'slug'; + } + + /** + * Retrieve the model for a bound value. + * Supports both slug and ID for backwards compatibility. + * + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + */ + public function resolveRouteBinding($value, $field = null) + { + // First try to find by slug + $document = $this->where('slug', $value)->first(); + + // If not found by slug, try by ID (for backwards compatibility) + if (!$document && is_numeric($value)) { + $document = $this->where('id', $value)->first(); + } + + return $document; + } + /** * The attributes that are mass assignable. * diff --git a/src/resources/views/livewire/quick-switcher.blade.php b/src/resources/views/livewire/quick-switcher.blade.php index 86c5bf1..a7e67b9 100644 --- a/src/resources/views/livewire/quick-switcher.blade.php +++ b/src/resources/views/livewire/quick-switcher.blade.php @@ -68,7 +68,7 @@ class="w-full pl-10 pr-4 py-3 border-0 focus:ring-0 text-lg" @foreach($this->results as $index => $result)