2

I'm using required if in Laravel validation, but it doesnt work. what is my mistake?

public function rules()
{
    if (!empty($this->game_id)) {
                $game = Game::find($this->game_id);
                $game_type = $game->type;
            } else {
                $game_type = 'sport';
            }

   return [
                'game_id' => 'required',
                'platform_id' => 'required_if:' . $game_type . ',==,electronic',
          ]
}
3
  • Please check this stackoverflow.com/questions/37777265/…
    – Jayson
    Commented Feb 5, 2019 at 8:46
  • 1
    your field name game_type seems to be dynamic, make sure it's an valid input name
    – Marcin
    Commented Feb 5, 2019 at 8:46
  • yes, its value is sport or electronic. I would like to required it when game_type is equals to electronic. Commented Feb 5, 2019 at 8:49

3 Answers 3

5

You don't need the whole expression, the correct format is as follows:

 return [
                'game_id' => 'required',
                'platform_id' => 'required_if:columnName:value',
          ];
3
1

Try the below code

public function rules()
{
    if (!empty($this->game_id)) {
                $game = Game::find($this->game_id);
                $game_type = $game->type;
            } else {
                $game_type = 'sport';
            }

   return [
                'game_id' => 'required',
                'platform_id' => 'required_if: . $game_type . ,==,electronic',
          ]
}

The syntax for required_if is 'field_name' => 'required_if:columnName:value'. What you're doing is wrapping the columnName in '' single quotes!

4
  • Thanks for your response. The columnName is from another table. how can I call it in this columnName? Commented Feb 5, 2019 at 8:54
  • What exactly you want to do? Commented Feb 5, 2019 at 8:59
  • User create a tournament. When he/she select a game_id, I will check its type as game_type from game table. The platform_id in tournament table is required if the game_type of that game_id is equal to electronic. Commented Feb 5, 2019 at 9:05
  • @ShokouhDareshiri did you tried my code? I got what you're trying to do but this code will work give a try and let me know. Commented Feb 5, 2019 at 9:12
1

I solved it in my own rules as below:

if (!empty($this->game_id)) {

      $game = Game::find($this->game_id);
      $game_type = $game->type;

          if($game_type == 'electronic'){
                  $required = 'required';
                } else{
                    $required = ' ';
                }

          }

return [
         'game_id' => 'required',
         'platform_id' => $required,
       ]
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.