【问题标题】:Enabling laravel 4 route to read slug instead of id启用 laravel 4 路由来读取 slug 而不是 id
【发布时间】:2014-04-28 16:44:36
【问题描述】:

我在 laravel 中有以下路线。

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

如果id 对应于数据库中的 id,例如:site.com/23,那么我可以从具有该特定 id 的数据库中获取结果。但是,如果我想获取类似标题 slug ex: site.com/this-is-title 的东西,那么它根本不起作用。我不知道如何告诉 laravel 基于数据库 id 以外的任何内容进行查询。

我的控制器是:

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

这是我的模板。

@extends("layouts.master")

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

@stop

没有输出。如果我这样做&lt;?php var_dump($result) ?&gt;,我会得到NULL

但正如我所说,如果我传递了一个 ID site.com/32,那么我会从数据库 a 中获得该 ID 的结果。

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    您可能会使用路线模型:

    解决方案 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);
        }
    }
    

    解决方案 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());
        }
    }
    

    文档可用here

    【讨论】:

    • 如何在我的配置文件操作中简单地检查 slug 是否存在于数据库中?
    • 您必须使用自己的型号名称。我刚刚假设你已经这样命名了你的模型。
    【解决方案2】:
    class HomeController extends BaseController{
        public function profile($company_slug){
            $result = Clients::where('company_slaug', '=', $company_slug)->get();
            if (empty($result)) {
                //not found
            }
            return View::make("home.profiles", compact("result"));
        }
    }
    

    【讨论】:

    • 谢谢。这种方法奏效了。通过我在我的模板中获取一个对象。 profiles.blade.php 如果我这样做 var_dump($result) 为什么它会返回一个雄辩的对象?我只想获取像{{ $result-&gt;title}} 这样的行有什么想法可以实现吗?
    猜你喜欢
    • 2014-10-23
    • 2013-03-14
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 2017-07-28
    • 2021-06-05
    相关资源
    最近更新 更多