如何验证 Laravel 请求中的选择
How to validate selection in Laravel Request
我正在构建一个应用程序来创建足球(英式足球)比赛。创建比赛时,我需要检查所选球队是否在所选联赛中。
提交表单时,我想显示一条消息,说明选择了错误的联赛。
控制器中有store()
方法
$match = new Match;
$match->round = $request->round;
$match->league_id = $request->league;
$match->home_team_id = $request->home_team;
$match->away_team_id = $request->away_team;
$match->match_date = $request->match_date;
$match->location = $request->location;
团队模型:
class Team extends Model
{
public function league() {
return $this->belongsTo('App\League');
}
}
联赛模型:
class League extends Model
{
public function teams() {
return $this->hasMany('App\Team');
}
}
这是 Laravel docs 验证
如果不存在 id
给定的联赛 league_id
,您可以使用关闭规则验证传入请求以对 return true
进行数据库查询] 并让团队具有给定的 home_team_id
和 away_team_id
。然后如果联盟不存在,则抛出验证失败:
$request->validate([
'home_team_id' => ['required'],
'away_team_id' => ['required'],
'league_id' => [
'required',
function ($attribute, $value, $fail) {
$condition = League::where('id', request('league_id')
->whereHas('teams', function($q) {
$q->where('id', request('home_team_id'))->where('id', request('away_team_id'));
})->doesntExist();
if ($condition) {
$fail('Both Teams must belong to the selected League.');
}
},
],
]);
参考文献:
- 验证Using Closures.
- Eloquent Querying Relationship Existence.
- 数据库查询生成器Determining If Records Exist。
我正在构建一个应用程序来创建足球(英式足球)比赛。创建比赛时,我需要检查所选球队是否在所选联赛中。
提交表单时,我想显示一条消息,说明选择了错误的联赛。
控制器中有store()
方法
$match = new Match;
$match->round = $request->round;
$match->league_id = $request->league;
$match->home_team_id = $request->home_team;
$match->away_team_id = $request->away_team;
$match->match_date = $request->match_date;
$match->location = $request->location;
团队模型:
class Team extends Model
{
public function league() {
return $this->belongsTo('App\League');
}
}
联赛模型:
class League extends Model
{
public function teams() {
return $this->hasMany('App\Team');
}
}
这是 Laravel docs 验证
如果不存在 id
给定的联赛 league_id
,您可以使用关闭规则验证传入请求以对 return true
进行数据库查询] 并让团队具有给定的 home_team_id
和 away_team_id
。然后如果联盟不存在,则抛出验证失败:
$request->validate([
'home_team_id' => ['required'],
'away_team_id' => ['required'],
'league_id' => [
'required',
function ($attribute, $value, $fail) {
$condition = League::where('id', request('league_id')
->whereHas('teams', function($q) {
$q->where('id', request('home_team_id'))->where('id', request('away_team_id'));
})->doesntExist();
if ($condition) {
$fail('Both Teams must belong to the selected League.');
}
},
],
]);
参考文献:
- 验证Using Closures.
- Eloquent Querying Relationship Existence.
- 数据库查询生成器Determining If Records Exist。