如何修改这个Laravel路由以便媒体按id搜索,但是在URL中显示了slug?

时间:2018-04-02 18:49:02

标签: php laravel laravel-5.1 laravel-routing laravel-controller

由于以下代码网址如下所示:/downloadpage/34 我想使URL SEO友好,如:/downloadpage/slug

在表格'媒体'有一列slug。如何在此代码中更改媒体按ID搜索,但在URL中显示slug?

routes.php文件:

Route::get('/downloadpage/{id}', [
    'as' => 'downloadpage', 'uses' => 'DownloadController@index'

DownloadController.php文件:

public function index($id){
    $images   = DB::table('media')->where("id", "=", $id)->get();
    $popular  = DB::table('media')->orderBy('count_download', 'DESC')->take(5)->get();
    $mostlike = DB::table('media')->orderBy('count_like', 'DESC')->take(5)->get();
    $alsolike = DB::table('media')->orderByRaw("RAND()")->where("id", "!=", $id)->take(3)->get();
    $settings = Setting::first();
    $previous = DB::table('media')->where('id', '<', $id)->max('id');
    $next     = DB::table('media')->where('id', '>', $id)->min('id');
    $imgshare = DB::table('media')->where("id", "=", $id)->first();
    return view('download.downloadpage', ['images'=>$images , 'popular'=>$popular, 'mostlike'=>$mostlike, 'alsolike'=>$alsolike, 'settings'=>$settings, 'previous'=>$previous, 'next'=>$next, 'imgshare'=>$imgshare]);
}

1 个答案:

答案 0 :(得分:1)

类似的东西。

路线:

Route::get('/downloadpage/{slug}', [
    'as' => 'downloadpage', 'uses' => 'DownloadController@index'

控制器:

public function index($slug){
    $images   = DB::table('media')->where("slug", "=", $slug)->first();
    $popular  = DB::table('media')->orderBy('count_download', 'DESC')->take(5)->get();
    $mostlike = DB::table('media')->orderBy('count_like', 'DESC')->take(5)->get();
    $alsolike = DB::table('media')->orderByRaw("RAND()")->where("id", "!=", $id)->take(3)->get();
    $settings = Setting::first();
    $previous = DB::table('media')->where('id', '<', $images->id)->max('id');
    $next     = DB::table('media')->where('id', '>', $images->id)->min('id');
    return view('download.downloadpage', ['images'=>$images , 'popular'=>$popular, 'mostlike'=>$mostlike, 'alsolike'=>$alsolike, 'settings'=>$settings, 'previous'=>$previous, 'next'=>$next, 'imgshare'=>$images]);
}

我将$images = DB::table()...->first()行更改为以->first()结束,因此您没有获得数组。您可能还需要在视图中更改某些内容。

我强烈建议您浏览routing的基本Laravel文档,这清楚地解释了这一点。并浏览Eloquent文档并将DB调用转换为模型。