将 2 个参数从路由传递到 Laravel 4 中的控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23510452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:29:46  来源:igfitidea点击:

pass 2 parameters from route to controller in Laravel 4

phplaravellaravel-4

提问by keatwei

Route

路线

Route::get('/site/{site_name_en}/{id}', array(
    'as' => 'profile-site',
    'uses' => 'ProfileController@site'
));

Controller

控制器

class ProfileController extends BaseController{

    public function site($id, $site_name_en){
        $site = Site::where('id', '=', $id)
            ->where('site_name_en', '=', $site_name_en);

        if($site->count()){
            $site = $site->first();
            return View::make('profile.site')
                ->with('site', $site);
        }
        return App::abort(404);
    }
}

What I'm trying to achieve is: that when I visit the following URL www.domain.com/site/abc/123456, it will shown the correct page based on the parameters. Is the whereclause correct? (because I couldn't retrieve the value)

我想要实现的是:当我访问以下 URL 时www.domain.com/site/abc/123456,它将根据参数显示正确的页面。是where条款是否正确?(因为我无法检索该值)

回答by Damien Pirsy

Your route

你的路线

Route::get('/site/{site_name_en}/{id}',

says the 1st parameter is site name, the second the id, but your controller function has the arguments swapped. You should call it:

说第一个参数是站点名称,第二个参数是 id,但是您的控制器函数交换了参数。你应该称之为:

public function site($site_name_en, $id){
   // rest of code
}

parameters are automatically passed down in the order they are defined by the route, and are not recognized by the variable name (IIRC).

参数会按照路由定义的顺序自动向下传递,并且不会被变量名 (IIRC) 识别。

As for the rest of your function I can't really tell if you're doing right or not, but I can suggest this:

至于您的其余功能,我真的无法判断您是否做得对,但我可以建议:

$site = Site::where('id', '=', $id)
            ->where('site_name_en', '=', $site_name_en)
            ->first();
if($site){
   return View::make('profile.site');
}
return App::abort(404);

Alternatively, you could use firstOrFail(), which throws a ModelNotFoundExceptionif the record is not found that you can catch with App::error()for example (an implementation is outlined in the manual)

或者,您可以使用firstOrFail(),ModelNotFoundException如果找不到您可以捕获的记录,则抛出 a App::error()(手册中概述了一个实现)