doulangpeng3933 2014-11-21 04:07
浏览 77
已采纳

Laravel通过参数路由到控制器

I'm trying to have clean URLs with out the ID displayed. For example, I currently have:

/Article/2 
/Article/3 
...

Instead I want those urls to switch to something like this:

/Article/2/ -> /My_Super_Awesome_Article/  
/Article/3/ -> /Another_Cool_Article

My route looks like this:

Route::resource('/article', 'ArticleController');

And the controller like this:

class MenuController extends \BaseController {

    public function show($id)
    {
            $page = Model::FindOrFail($id);
            return View::make('article.show')->withPage($page);
    }

    // more functions

===================================================

WHAT WORKS BUT I THINK IS A BAD WAY OF DOING IT:

I figure out a way to do this... but this is for sure not the best approach. This is the technique I'm currently using to substitute:

In the controller, I add this

public function Clean_Url_20()
    {
            $page = Model::FindOrFail( 20 );
            return View::make('article.show')->withPage($page);
    }

And in the routes, I use this:

Route::get('/My_Super_Cool_URL', 'ArticleController@Clean_Url_20');

So... Is there a better way to achieve this?

  • 写回答

2条回答 默认 最新

  • douju6752 2014-11-21 05:48
    关注

    You lack flexibility if you give every single article a route. You have to define 1000 routes if you have 1000 articles.

    Why not define these routes in another way? For example:

    Route::get('article/{articleSlug}','ArticlesController@show');
    

    In your controller you just use the slug to find a particular article.

    By the way, you can use Str::slug() to format your article titles when you are preparing your article data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘