Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Array in Laravel

I would need to Validate my inputted data, and it says

htmlentities() expects parameter 1 to be string, array given (View: /var/www/mw/app/views/delivery-reports/edit.blade.php)

Here is my Method:

 public static $rules_imei = array(
        'imei'             => 'required|alpha_dash|min:2',

         );

My Rules:

  public function __construct(
        DeliveryReport $delivery_report)
    {
        $this->deliveryReport = $delivery_report;
    }

this my controller validation:

 $data = Input::get('imei');

if($errors = $this->deliveryReport->isInvalidImei($data))
{
    return Redirect::back()->withInput()->withErrors($errors);
}

Here is my view:

@for ($qty = 0; $qty < $item_quantity; $qty++)
<br>
{{Form::text('imei[]',$qty)}}
<br>
@endfor
like image 834
Martney Acha Avatar asked Jan 11 '23 04:01

Martney Acha


2 Answers

Updated Answer (For old answer check the history)

There is undocumented core support for this (Thanks to Andreas Lutro for the hint).

$validator = Validator::make(Input::all(), []);
$validator->each('imei', ['required', 'alpha_dash', 'min:2']);

No extension needed.

Further Reading

  • API-Docs
like image 118
thpl Avatar answered Jan 15 '23 01:01

thpl


Make indexed array on view

@for ($qty = 0; $qty < $item_quantity; $qty++)
<br>
{{Form::text('imei['.$qty.']',$qty)}}
<br>
@endfor

Go through the loop to validate each

    $rules_imei = [];
    //make custom rule for each element of array
    foreach(Input::get('imei') as $k => $val){
       $rules_imei[$k] = 'required';
    }
    //to have custom message like '1st imei is required' 
    $niceNames = array(
        '0' => '1st imei',
        '1' => '2nd imei',
        '2' => '3rd imei',
        '3' => '4th imei'

    );      
    $v = Validator::make(Input::get('imei'), $rules_imei);
    $v->setAttributeNames($niceNames); 


    if ($v->fails())
    {
        return Redirect::back()->withErrors($v)->withInput();

    }

With this validation each option is compulsary, you can change as per your need

like image 39
sumit Avatar answered Jan 15 '23 02:01

sumit