0

Laravel sends array to field name row This basically looks like:

    [row] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
            [5] => b_number
            [6] => u_number
            [7] => 
            [8] => 
            [9] => a_name
            [10] => a_value
            [11] => c_name
            [12] => floor
            [13] => stack
        )

This array could have value at different index and this array could be big as well as small than this. But main requirement is to check either

b_number,
u_number, 
a_name,
a_value, 
c_name, 
floor, 
stack

these value are present on the array. And if some value is missing I need to return error as.

b_numbber is required c_name is required

UPTO NOW WHAT I HAVE DONE:

$rules = [
            'row' => [new RequiredCSVColumn()]
        ];

RequiredCSVColumn

    public function passes($attribute, $value)
    {
        $arr = array();
        $required_all = array('b_number', 'u_number', 'a_name' ,'a_value', 'c_name', 'floor', 'stack');

        foreach ($required_all as $k => $v) {
            if(!in_array($v,$value))
            {
                $arr[] = $v;
            }
        }
        if(!empty($arr)){
            return false;
        }
        return true;

    }

Here, $arr holds the name of field which are missing all I need is to return this message as Field Name is required

1 Answer 1

2

You have to return custom message like this

class RequiredCSVColumn implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($message = null)
    {
        $this->message = $message;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
         $arr = array();
         $required_all = array('b_number', 'u_number', 'a_name' ,'a_value', 'c_name', 'floor', 'stack');

         foreach ($required_all as $k => $v) {
            if(!in_array($v,$value))
            {
                $arr[] = $v;
                $this->message += $v." is required ";
            }
         }
        if(!empty($arr)){
           return false;
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
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.