How to validate selection in Laravel Request

Viewed 136

I am building an app to create Football (Soccer) matches. When I create a match, I need to check that the selected teams are in the chosen league.

When the form is submitted I would like to display a message that the wrong league selected if so.

There is store() method in controller

$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;

Team model:

class Team extends Model
{
    public function league() {
        return $this->belongsTo('App\League');
    }
}

League model:

class League extends Model
{
    public function teams() {
        return $this->hasMany('App\Team');
    }
}
2 Answers

You can validate the incoming request using a closure rule to make a database query to return true if does not exist the League which id is the given league_id and have the teams with the given home_team_id and the away_team_id. Then if the League doesn't exists, throw a validation fail:

$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.');
            }
        },
    ],
]);

References:

Related