2017-03-09 65 views
1

段塞我有一個像/locations/name-of-the-location.IDLaravel:檢查蛞蝓的路線是等於在數據庫

我的路線的網址是:

Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => '[email protected]'])->where([ 
    'location' => '[0-9]+', 
    'slug' => '[a-z0-9-]+' 
]); 

現在我要檢查,如果提供的鼻涕蟲是一樣的用我的模型保存在數據庫列'slug'中(因爲slug可能已經改變)。如果沒有,那麼我想重定向到正確的路徑。

哪裏可以做到這一點?我想到了\ App \ Providers \ RouteServiceProvider-但是當我嘗試在那裏使用Route::currentRouteName()時,我得到NULL,可能是因爲在RouteServiceProvider的boot()方法中對於該方法來說「太早」。

我可以做的是使用path(),但對我來說這看起來有點髒,因爲我使用其他語言的路由前綴。

這裏就是我想(我用一個小的輔助類RouteSlug) - 當然這是行不通的:

public function boot() 
{ 
    parent::boot(); 

    if (strstr(Route::currentRouteName(), '.', true) == 'locations') 
    { 
     Route::bind('location', function ($location) { 
      $location = \App\Location::withTrashed()->find($location); 
      $parameters = Route::getCurrentRoute()->parameters(); 
      $slug = $parameters['slug']; 

      if ($redirect = \RouteSlug::checkRedirect(Route::getCurrentRoute()->getName(), $location->id, $location->slug, $slug)) 
      { 
       return redirect($redirect); 
      } 
      else 
      { 
       return $location; 
      } 

     }); 
    } 
} 
+0

爲什麼不把這個'LocationsController @ show'? – upful

+0

我也使用編輯,銷燬和其他方法的slu g。我也有其他控制器中的slu so,所以我想在一個地方管理所有重定向。 – sugo

+0

爲什麼重新發明輪子? https://github.com/cviebrock/eloquent-sluggable – ceejayoz

回答

0

所以最後我想出了一箇中間人分別是:

應用程序\ HTTP \中間件\ CheckSlug

public function handle($request, Closure $next) 
{ 
    if ($redirect = RouteSlug::checkRedirect(Route::currentRouteName(), $request->location->id, $request->location->slug, $request->slug)) 
    { 
     return redirect($redirect); 
    } 

    return $next($request); 
} 

我的路線是這樣的:

Route::get('locations/{slug}.{location}', ['as' => 'locations.show', 'uses' => '[email protected]'])->where([ 
    'location' => '[0-9]+', 
    'slug' => '[a-z0-9-]+' 
])->middleware(App\Http\Middleware\CheckSlug::class); 
+1

你應該註冊你的中間件:https://laravel.com/docs/5.4/middleware#registering-middleware – upful

+0

是的,我也這麼認爲。明天我會改善這一點。現在我很高興我的解決方案能夠正常工作。 – sugo

0

您的路線應該是這樣的:

Route::get('locations/{id}/{slug}', ['as' => 'locations.show', 'uses' => '[email protected]'])->where([ 
    'id' => '[0-9]+', 
    'slug' => '[a-z0-9-]+' 
]); 

而且[email protected]應看起來像這樣:

public function show($id, $slug) 
{ 
    // Add 'use App\Location' to the top of this controller 
    $location = Location::find($id); 

    // I'm not sure what you were doing with the soft deleted items 
    // but you might want to restore them if you are using them 
    if ($location->trashed()) $location->restore(); 

    if ($slug != $location->slug) { 
     return redirect()->route('locations.show', ['id' => $id, 'slug' => $location->slug]); 
    } 

    // Return the view 

} 
+0

不,我的路線應該和我的問題完全一樣。我也使用路由模型綁定,所以不需要'$ location = Location :: find($ id);' – sugo

+0

路由模型綁定僅在您打算僅返回模型時有用,您是否在製作API? – upful

+0

我使用路由模型綁定爲了也得到軟刪除模型,當我鍵入提示他們在我的控制器。 – sugo