How to add slug and ID URL to Laravel 4 Route?

前端 未结 3 1818
没有蜡笔的小新
没有蜡笔的小新 2021-02-10 03:08

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 b

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-10 03:25

    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!

提交回复
热议问题