0

I have the following array of fields:

$fields = [
    'name'     => [
        'label' => 'Company Name' . $req,

     ],
     'address1' => [
     'label' => 'Address' . $req
     ],
    'address2' => [
        'label' => 'Address (Line 2)'
     ],
    'zip'      => [
        'label' => 'Zip/Postal Code'
     ],

    'phone'   => [
        'label' => 'Office Phone',
        'val'   => dotted($active->office)
     ],
    [
        'type'  => 'submit',
        'label' => "Save",
        'class' => 'btn btn-primary !important'
    ]
];

I need to validate the field 'phone' to make sure that it is 10 digits, all numbers. What can I add here to check this here, or should I validate it somewhere else?

1 Answer 1

1

There are multiple ways you can go about validation using Laravel. Personally, I follow making a new Request class for what Model I am storing and type hint the request in the Controller function. This is my flow, but again, there are several ways to utilize Laravel validation. Below is an example. You would name the classes what you want.

From CLI

php artisan make:request StoreUserDataRequest

Within StoreUserDataRequest class have this function that has your validation rules for each field

public function rules()
    {
        $phonePattern = '/\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/';
        return [
            'name' => 'required|unique|max:255',
            'address1' => 'required',
            'address2' => 'required',
            'zip' => 'required',
            'phone' => 'required|regex:' . $phonePattern
        ];
    }

Within your controller method

  public function store(StoreUserDataRequest $request)
    {
        // do whatever if validation passes.
    }

When the store method is called, the parameters in the $request have to pass the validation rules or it fails. If you want to review the other validation techniques using laravel, go here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.