我试图在一个简单的投票应用程序中通过后退按钮防止重复提交
我以前做过这个。投票之后,它返回这个视图
return View::make('votes.votesresults')->with('candidates',$candidates)->with('count',$count);
这将两个变量传递给votesresult
视图,但不幸的是,如果有人单击后退按钮,他们可以重新提交他们的投票。我环顾四周,发现了PRG模式。我应该使用重定向来防止这种情况。所以我尝试了
return Redirect::route('votes.votesresults')->with('candidates',$candidates)->with('count',$count);
这是我的控制器
public function votesuccess()
{
$rules = array(
'name' => 'required'
);
$validator = Validator::make(Input::all(),$rules);
if ($validator->fails()) {
return Redirect::to('votes/index')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$vote = new Vote;
$candidates = Candidate::all();
$candidate_id =Input::get('name');
$candidate = Candidate::find($candidate_id);
$vote = $candidate->votes()->save($vote);
//$count = DB::table('votes')->where('candidate_id','=','$candidate_id')->count();
$count = DB::table('votes')->count();
// redirect
Session::flash('message', 'Successfully Cast your vote!');
//return View::make('votes.voteresults')->with('candidates', $candidates)->with('count',$count);
return Redirect::route('voteresults')->with('candidates', $candidates)->with('count',$count);
}
}
public function voteresult()
{
$candidates = Candidate::all();
return View::make('votes.voteresults');
}
我的路线是这样的
Route::post('votesuccess', array('as' => 'votesuccess', 'uses'=>'VoteController@votesuccess'));
Route::get('voteresults', array('as' => 'voteresults', 'uses'=>'VoteController@voteresult'));
这不起作用,因为它返回undefined variable: candidates
。我的结果视图需要这些变量。那么我如何正确地实现PRG模式以防止双重提交同时能够将数据传递给我的视图
您正在重定向到名为voteresults
的路由,该路由由voteresult
函数处理,而不是votesuccess
函数。
在votesuccess
函数中,您应该加载视图并在该视图中包含candidates
变量。您可以使用Session::get('candidates')
访问存储在会话中的candidates
变量。
这将有助于看到您的选民结果视图,看看那里发生了什么,以及您在哪里/如何放入逻辑以避免重复提交。您是否担心意外的重复提交,或者只是来自同一用户的多次提交?如果是后者,那么您需要构建一些逻辑来限制用户只能投1票。您可以通过检查用户是否有相关的投票来做到这一点。
if ( ! $candidate->votes() ) {
// no votes exist, proceed with storing vote
}
下面是你的控制器重构:
public function votesuccess()
{
$rules = array(
'name' => 'required'
);
$validator = Validator::make(Input::all(),$rules);
if ($validator->fails()) {
return Redirect::back('votes/index')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$candidate = Candidate::find(Input::get('name'));
$vote = $candidate->votes()->save(new Vote);
// redirect
Session::flash('message', 'Successfully Cast your vote!');
return Redirect::route('voteresults');
}
}
public function voteresult()
{
$candidates = Candidate::all();
$count = DB::table('votes')->count();
return View::make('votes.voteresults', compact('candidates', 'count'));
}