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

前端 未结 3 1820
没有蜡笔的小新
没有蜡笔的小新 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:46

    I wouldn't pass two parameters to your function, just treat it like an ID in both cases. You'll need to add a "slug" column to your db if you haven't already and make sure those values are unique just like an id. Then in your controller you can do something like this:

    public function getCampaignMap($id){
        //look for the campaign by id first
        $campaignmap  = Campaign::find($id);
        //if none is found try to find it by slug instead
        if(!$campaignmap){
            $campaignmap = Campaign::where('slug','=',$id)->firstOrFail();
        }
        return View::make('campaignmap.show', compact('campaignmap'));
    }
    

    You could also save yourself a query in some cases by checking to see if the id is numeric and then just look for it by slug if it's not numeric such as:

    public function getCampaignMap($id){
        //look for the campaign by id if it's numeric and by slug if not
        if(is_numeric($id)){
             $campaignmap  = Campaign::find($id);
        }else{
             $campaignmap = Campaign::where('slug','=',$id)->firstOrFail();
        }
        return View::make('campaignmap.show', compact('campaignmap'));
    }
    

提交回复
热议问题