duanqiongchong0354 2014-04-28 16:44
浏览 38

启用laravel 4 route来读取slug而不是id

I have the following route in laravel.

Route::get('/{id}', 'HomeController@profile')->where('id', '[0-9A-Za-z\-]+');

If id corresponds to id in a database, ex: site.com/23 then I am able to fetch results from database with that specific id. However, if I want to fetch something like a title slug ex: site.com/this-is-title then it won't work at all. I have no idea how to tell laravel to query based on anything other than an database id.

My controller is:

class HomeController extends BaseController{
        public function profile($company_slug){
        $result = Clients::all($company_slug); 
        return View::make("home.profiles", compact("result"));
    }
}

Here is my template.

@extends("layouts.master")

@section("main-content")
<?php
   {{ $result->company_slug }}
?>

@stop

There is no output. If I do <?php var_dump($result) ?> I get NULL.

But as I said, if I pass an id site.com/32 then I get result from database a for that id.

  • 写回答

2条回答 默认 最新

  • dsebywql016137 2014-04-28 16:53
    关注

    You might use the route models:

    Solution 1:

    Route::bind('profiles', function($value) 
    {
        $records = Profiles::where('company_slug', $value)->all();
    
        if ( ! $records->count())
        {
            App::abort(404);
        }
        else 
        {
            return $records;
        }
    });
    
    Route::get('{profiles}', 'HomeController@profile');
    
    class HomeController extends BaseController
    {
        public function profile($profiles)
        {
            return View::make("home.profiles")->with('profiles', $profiles);
        }
    }
    

    Solution 2:

    Route::get('{slug}', 'HomeController@profile');
    
    class HomeController extends BaseController
    {
        public function profile($slug)
        {
            return View::make("home.profiles")
                ->with('profiles', Profiles::where('company_slug', $slug)->all());
        }
    }
    

    Docu is available here.

    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗