簡體   English   中英

Laravel:檢查路線中的slug是否等於數據庫中的slug

[英]Laravel: Check if slug in a route is equal to slug in database

我有一個像/locations/name-of-the-location.ID這樣的網址

我的路線是:

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

現在我想檢查提供的slug是否與我的模型在數據庫列'slug'中保存的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;
            }

        });
    }
}

您的路線應如下所示:

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

LocationsController@show應該如下所示:

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

}

最后我想出了一個中間件:

應用程序\\ 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' => 'LocationsController@show'])->where([
    'location' => '[0-9]+', 
    'slug' => '[a-z0-9-]+'
])->middleware(App\Http\Middleware\CheckSlug::class);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM