How do I pass a hard coded variable to a controller?

My route is:

Route::group(array('prefix' => $locale), function() {
    Route::get('/milk', array('as' => 'milk', 'uses' => 'ProductsController@index'));
});

我想做一些事情,比如:

Route::get('/milk', array('as' => 'milk', 'uses' => 'ProductsController@index(1)'));

但那不管用.

How can this be done?


如果我没有解释清楚,很抱歉.

I wish to simply hardcode (set in stone by me) the type_id for certain routes like so:

Route::get('/milk', array('as' => 'milk', 'uses' => 'ProductsController@index(1)'));
Route::get('/cheese', array('as' => 'cheese', 'uses' => 'ProductsController@index(2)'));
...

我的ProductsController供参考:

class ProductsController extends BaseController {

    public function index($type_id) {
        $Products = new Products;
        $products = $Products->where('type_id', $type_id)->get();
        return View::make('products.products', array('products' => $products));
    }

}

推荐答案

您可以对路由使用闭包,然后调用控制器操作:

Route::get('/milk', array('as' => 'milk', function(){
    return App::make('ProductsController')->index(1);
}));

然而,更好的方法是使用where条件,然后在控制器中进行类型到id的转换.但是,您将丢失直接别名,并且在生成URL时必须将产品作为参数传入.

Route::get('{product}', array('as' => 'product', 'uses' => 'ProductsController@index'))
    ->where('product', '(milk|cheese)');

Laravel相关问答推荐

Laravel将变量从模板到已发布的供应商模板

Livewire 3分页在点击后不更新页面

如何使用PHP版本8.2.6安装beyondcode/laravel-websockets软件包?

Laravel 验证 - 不同的属性规范

自从 Laravel 使用 Vite 更新后,我无法运行npm run dev

Laravel 集合排序不生效

Laravel - 将变量从中间件传递到控制器/路由

使用 Laravel 限制多态多对多关系中的相关记录

在 Laravel Blade 中转义 vue.js 数据绑定语法?

Laravel whereDoesntHave() - 多个 OR 条件

laravel 预期响应代码 250 但得到代码530

Laravel - 自定义时间戳列名称

Laravel 5.4 有时验证规则不起作用

Laravel 全部返回 ID 变为 0

Laravel 5 Mime 验证

将自定义消息(或任何其他数据)传递给 Laravel 404.blade.php

Laravel 5 默认注册后如何发送邮件?

基于日期的 Laravel 日志(log)文件

如何使用 Postman 处理 Laravel $_POST 请求

如何从 PHPUnit 测试设置运行 Laravel 数据库 seeder 机?