简体   繁体   English

在Laravel中将固定变量从路由传递到控制器

[英]Pass fixed variable from route to controller in Laravel

I'm trying to pass a variable through my route to my controller, but I have multiple routes (categories) leading to the same controller ie 我正在尝试将变量通过路由传递给控制器​​,但是我有多个路由(类别)通向同一控制器,即

Route::get('/category1/{region}/{suburb?}', 'SearchController@search');
Route::get('/category2/{region}/{suburb?}', 'SearchController@search');

Making /category1, 2, etc. to be a parameter /{category} is not an option and I don't want to make separate controller function for each category. 将/ category1、2等作为参数/ {category}并不是一种选择,并且我不想为每个类别都设置单独的控制器功能。

How do I send the first segment of the url to my search controller? 如何将网址的第一部分发送到搜索控制器? ie category1 or category2? 即类别1或类别2?

At present controller is as follows: 目前的控制器如下:

public function search($region, $suburb = null) { }

Thanks! 谢谢!

You can specify a mask for your {category} parameter so that it must fit the format "category[0-9]+" in order to match the route. 您可以为{category}参数指定一个掩码,以使其必须符合格式“ category [0-9] +”才能匹配路由。

Route::get('/{category}/{region}/{suburb?}', 'SearchController@search')
    ->where('category', 'category[0-9]+');

Now, your example url (from the comments) www.a.com/var1/var2/var3 will only match the route if var1 matches the given category regex. 现在,您的示例网址(来自注释) www.a.com/var1/var2/var3仅在var1与给定类别正则表达式匹配时才与路由匹配。

More information can be found in the documentation for route parameters here . 可以在此处的路由参数文档中找到更多信息。

Edit 编辑

Yes, this can work with an array of string values. 是的,这可以使用字符串值数组。 It is a regex, so you just need to put your array of string values into that context: 这是一个正则表达式,因此您只需要将字符串值数组放入该上下文中即可:

Route::get('/{category}/{region}/{suburb?}', 'SearchController@search')
    ->where('category', 'hairdresser|cooper|fletcher');

Or, if you have the array built somewhere else: 或者,如果您在其他位置构建了阵列:

$arr = ['hairdresser', 'cooper', 'fletcher'];

// run each array entry through preg_quote and then glue
// the resulting array together with pipes
Route::get('/{category}/{region}/{suburb?}', 'SearchController@search')
    ->where('category', implode('|', array_map('preg_quote', $arr)));

Edit 2 (solutions for original request) 编辑2(原始请求的解决方案)

Your original question was how to pass the hardcoded category segment into the controller. 您最初的问题是如何将硬编码的类别段传递到控制器中。 If, for some reason, you didn't wish to use the solution above, you have two other options. 如果由于某种原因您不希望使用上述解决方案,则可以选择其他两种方法。

Option 1: don't pass the value in, just access the segments of the request in the controller. 选项1:不传递值,仅访问控制器中的请求段。

public function search($region, $suburb = null) {
    $category = \Request::segment(1);
    dd($category);
}

Option 2: modify the route parameters using a before filter (L4) or before middleware (L5). 选项2:使用前置过滤器(L4)或前置中间件(L5)修改路由参数。

Before filters (and middleware) have access to the route object, and can use the methods on the route object to modify the route parameters. 过滤器(和中间件)可以访问路由对象,并且可以使用路由对象上的方法来修改路由参数。 These route parameters are eventually passed into the controller action. 这些路由参数最终传递到控制器操作中。 The route parameters are stored as an associative array, so that needs to be kept in mind when trying to get the order correct. 路线参数存储为关联数组,因此在尝试正确获取订单时必须牢记。

If using Laravel 4, you'd need a before filter. 如果使用Laravel 4,则需要一个前置过滤器。 Define the routes to use the before filter and pass in the hardcoded value to be added onto the parameters. 定义路由以使用before过滤器,并传递要添加到参数中的硬编码值。

Route::get('/hairdresser/{region}/{suburb?}', ['before' => 'shiftParameter:hairdresser', 'uses' => 'SearchController@search']);
Route::get('/cooper/{region}/{suburb?}', ['before' => 'shiftParameter:cooper', 'uses' => 'SearchController@search']);
Route::get('/fletcher/{region}/{suburb?}', ['before' => 'shiftParameter:fletcher', 'uses' => 'SearchController@search']);

Route::filter('shiftParameter', function ($route, $request, $value) {
    // save off the current route parameters    
    $parameters = $route->parameters();
    // unset the current route parameters
    foreach($parameters as $name => $parameter) {
        $route->forgetParameter($name);
    }

    // union the new parameters and the old parameters
    $parameters = ['customParameter0' => $value] + $parameters;
    // loop through the new set of parameters to add them to the route
    foreach($parameters as $name => $parameter) {
        $route->setParameter($name, $parameter);
    }
});

If using Laravel 5, you'd need to define a new before middleware. 如果使用Laravel 5,则需要在中间件之前定义一个新的。 Add the new class to the app/Http/Middleware directory and register it in the $routeMiddleware variable in app/Http/Kernel.php. 将新类添加到app / Http / Middleware目录,并将其注册到app / Http / Kernel.php的$routeMiddleware变量中。 The logic is basically the same, with an extra hoop to go through in order to pass parameters to the middleware. 逻辑基本上是相同的,但要经过额外的循环才能将参数传递给中间件。

// the 'parameters' key is a custom key we're using to pass the data to the middleware
Route::get('/hairdresser/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['hairdresser'], 'uses' => 'SearchController@search']);
Route::get('/cooper/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['cooper'], 'uses' => 'SearchController@search']);
Route::get('/fletcher/{region}/{suburb?}', ['middleware' => 'shiftParameter', 'parameters' => ['fletcher'], 'uses' => 'SearchController@search']);

// middleware class to go in app/Http/Middleware
// generate with "php artisan make:middleware" statement and copy logic below
class ShiftParameterMiddleware {
    public function handle($request, Closure $next) {
        // get the route from the request
        $route = $request->route();

        // save off the current route parameters
        $parameters = $route->parameters();
        // unset the current route parameters
        foreach ($parameters as $name => $parameter) {
            $route->forgetParameter($name);
        }

        // build the new parameters to shift onto the array
        // from the data passed to the middleware
        $newParameters = [];
        foreach ($this->getParameters($request) as $key => $value) {
            $newParameters['customParameter' . $key] = $value;
        }

        // union the new parameters and the old parameters
        $parameters = $newParameters + $parameters;
        // loop through the new set of parameters to add them to the route
        foreach ($parameters as $name => $parameter) {
            $route->setParameter($name, $parameter);
        }

        return $next($request);
    }

    /**
     * Method to get the data from the custom 'parameters' key added
     * on the route definition.
     */
    protected function getParameters($request) {
        $actions = $request->route()->getAction();
        return $actions['parameters'];
    }
}

Now, with the filter (or middleware) setup and in use, the category will be passed into the controller method as the first parameter. 现在,随着过滤器(或中间件)的设置和使用,该类别将作为第一个参数传递到控制器方法中。

public function search($category, $region, $suburb = null) {
    dd($category);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM