Search code examples
laravellaravel-validation

Confused about Laravel "sometimes" validation works


I'm really confused about why this is happening? I had successfully added a record then when I tried to update the record It says that the field is required even I passing it already. Then when I tried to add "sometimes" on the validation. Now, it works. Why? Please enlighten me. Thank you!

my Test Model

This was the result when I tried to remove "sometimes"


Solution

  • sometimes is when you sometimes include the field.

    Let's see an example of validation when creating a user:-

    $validation = [
     "name" => "required|string|",
     "email" => "required|email",
     "hobbies" => "sometimes|array"
    ];
    

    Sample payloads

    {
     name: "Bob",
     email: "bob@gmail.com"
    }
    // this will pass
    
    {
     name: "Bob",
     email: "bob@gmail.com",
     hobbies: ["fishing", "swimming"]
    }
    // this would also pass
    
    {
     name: "Bob",
     email: "bob@gmail.com",
     hobbies: "swimming"
    }
    // this would fail since it doesn't match "array" validation