我正在尝试在控制器中添加验证,但不能与auth:check一起使用。这是Laravel 5.7版。
这是验证存在问题的功能存储。
Map
[![在此处输入图片描述] [2]] [2]
更新 验证现在可以使用,但是产生了一个新问题。保存新播放器时,会显示此错误。
我认为问题是此代码
public function store(Request $request)
{
$request->validate([
'first_name' => ['required'|'min:2'|'max:50']
]);
if(Auth::check()){
$player = Player::create([
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name'),
]);
if($player){
return redirect()->route('players.show', ['player'=> $player->id])
->with('success' , 'foo');
}
}
return back()->withInput()->with('errors', 'Foo Error');
}
答案 0 :(得分:1)
您的大多数代码都是不必要的,您可以protect the route并删除其中的大部分代码:
public function store(Request $request)
{
// Your validation is not correct and you are missing the last_name.
// $request->validate() will return the validated data if
// the validation was successful
$request->validate([
'first_name' => ['required' | 'min:2' | 'max:50']
]);
// After protecting the route we can get rid of the auth check
if (Auth::check()) {
$player = Player::create([
// Since $request->validate returns the validated data, this is unncessary
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name'),
]);
// It will either create the player or throw an exception,
// this conditional seems unnecessary
if ($player) {
return redirect()
// If you setup your routes correctly you can pass the model to the route
// so ['player' => $player->id] is unnecessary
->route('players.show', ['player' => $player->id])
->with('success', 'foo');
}
}
// This return seems pointless since it can never be reached
// after protecting the route
return back()->withInput()->with('errors', 'Foo Error');
}
所以看起来像这样:
public function __construct()
{
$this->middleware('auth');
}
/**
* @param Request $request
*
* @return RedirectResponse
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'first_name' => 'required|min:2|max:50',
'last_name' => 'required|min:2|max:50',
]);
$player = Player::create($validatedData);
return redirect()
->route('players.show', $player)
->with('success', 'foo');
}