duanfoumi5620 2014-02-22 03:35
浏览 50

如何向Laravel 4 Route添加slug和ID URL?

I would like to add nice Slug URL to my Laravbel Project. I currently am using ID numbers.

My goal is to continue using Numbers but also to use Slugs for better SEO URL's. So either a Slug or an ID will load the proper page.

Below is my current Route that uses an ID number to load a record.

// View Campaign Details/Profile/Map View
Route::any("/campaign/{id}", array(
    "as"   => "campaign/{id}",
    "uses" => "CampaignController@getCampaignMap"
));

To be able to add Slug support in Laravel 4. I believe I need to add a slug database column to my campaigns table.

How would I go about editing my Route to work with an ID number of a slug string?

Also since I am only wanting to use slug on a couple sections of my application, how would I do my.htaccess for this, or is an.htaccess even required?

  • 写回答

3条回答 默认 最新

  • dsf5989 2014-02-22 09:11
    关注

    Consider using RESTful Controllers, this will generate a url based on the controller and function name:

    Route::controller('users', 'UserController');
    

    Also, I am pretty sure resource controllers does the same thing, although I have not used them yet:

    Route::resource('photo', 'PhotoController');
    

    If you still wish to define your routes, I would add a slug column to your DB and then your route would be:

    // View Campaign Details/Profile/Map View
    Route::any("/campaign/{slug}", array(
        "as"   => "campaign",
        "uses" => "CampaignController@getCampaignMap"
    ));
    

    Keep in mind the slug would have to be unique.

    In your controller:

    public function getCampaignMap($slug)
    {
        $campaignmap = YourModel::where('slug', '=', $slug)->get();
    }
    

    If you wish, you may still pass the id in as well:

    // View Campaign Details/Profile/Map View
    Route::any("/campaign/{slug}/{id}", array(
        "as"   => "campaign",
        "uses" => "CampaignController@getCampaignMap"
    ));
    

    Then, in your controller:

    public function getCampaignMap($slug, $id)
    {
        $campaignmap = YourModel::find($id);
    }
    

    Hope that helps!

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源