如何添加蛞蝓和ID的URL Laravel 4路线? [英] How to add slug and ID URL to Laravel 4 Route?

查看:163
本文介绍了如何添加蛞蝓和ID的URL Laravel 4路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想补充的很好弹头 URL我Laravbel项目。我目前正在使用的ID号。

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

我的目标是继续使用数字,但也使用蛞蝓更好的搜索引擎优化的URL。因此,无论是弹头或ID将加载正确的页面。

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.

下面是我的电流路线使用的ID号装载的记录。

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"
));

要能够增加弹头支持Laravel 4,我认为我需要一个塞数据库列添加到我的广告系列的表。

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

我怎么会去编辑我的路由与塞字符串的ID号来上班?

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

另外,因为我只是想用塞在我的应用程序的两节,我会怎么做my.htaccess这一点,或者an.htaccess甚至要求?

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?

推荐答案

我不会通过两个参数的功能,只是把它当作在这两种情况下的ID。你需要一个塞列添加到您的数据库,如果你还没有,并确保这些值是唯一的,就像一个ID。然后在你的控制器,你可以做这样的事情:

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'));
}

您也可以保存自己在某些情况下,查询通过检查,看是否id是数字,然后就寻找它由团状,如果它不是数字,如:

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'));
}

这篇关于如何添加蛞蝓和ID的URL Laravel 4路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆