【问题标题】:How to modify this Laravel route so that the media searches by id, but in the URL it shows slug?如何修改此 Laravel 路由,以便媒体按 id 搜索,但在 URL 中显示 slug?
【发布时间】:2018-09-12 00:09:56
【问题描述】:

由于下面的代码 URL 看起来像:/downloadpage/34 我想让 URL 对 SEO 友好,例如:/downloadpage/slug

在表“媒体”中有一个列slug。如何更改媒体通过 id 搜索的代码,但在 URL 中显示 slug?

routes.php 文件:

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

下载Controller.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]);
}

【问题讨论】:

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


    【解决方案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()...-&gt;first() 行更改为以-&gt;first() 结尾,因此您不会得到数组。您可能还需要更改视图中的某些内容。

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

    【讨论】:

    • 通过应用此更改,网址变为我想要的,但会出现很多错误。
    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2018-07-26
    相关资源
    最近更新 更多