Laravel:如何将值从表单传递给控制器​​?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17893495/
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 08:11:23  来源:igfitidea点击:

Laravel: how do I pass a value from a form to a controller?

phplaravellaravel-4

提问by Josh

I have a form:

我有一个表格:

{ Form::open(array('action' => 'RatesController@postUserRate', $client->id)) }}
    {{ Form::text('rate', '', array('placeholder' => 'Enter new custom client rate...')) }}
    {{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}

How do I pass my $client->id value through the form to my controller method?

如何通过表单将我的 $client->id 值传递给我的控制器方法?

I currently have a controller method that looks like this:

我目前有一个控制器方法,如下所示:

public function postUserRate($id)
{
    $currentUser = User::find(Sentry::getUser()->id);
    $userRate = DB::table('users_rates')->where('user_id', $currentUser->id)->where('client_id', $id)->pluck('rate');

    if(is_null($userRate))
    {
    ...
    }else{
    ....
    }
}

And the error log says "Missing argument 1 for RatesController::postUserRate()"

错误日志显示“RatesController::postUserRate() 缺少参数 1”

Any ideas on how to pass this $client->id into my controller so I can use it as I want to above?

关于如何将这个 $client->id 传递到我的控制器以便我可以像上面那样使用它的任何想法?

回答by JeffreyWay

Add {{ Form::hidden('id', $client->id) }}to the form. Then, when it's posted, you can fetch its value per usual with Input::get('id').

添加{{ Form::hidden('id', $client->id) }}到表单中。然后,当它发布时,您可以使用Input::get('id').

Also, remove the postUserRatemethod's argument.

此外,删除postUserRate方法的参数。

回答by zianwar

You simply use :

您只需使用:

Form::open(array('action' => array('Controller@method', $user->id)))

Form::open(array('action' => array('Controller@method', $user->id)))

  • the variable $user->idis passed as argument to the method method, also this last one should recieve an argument as well, like so : method($userId)
  • 变量$user->id作为参数传递给方法method,最后一个也应该接收一个参数,如下所示: method($userId)

Source : Laravel documentation

来源:Laravel文档