AngularAngularAngular
AngularAngularAngular

Reputation: 3769

How to set custom attributes for laravel validation instead of numeric keys?

How to send the values for laravel validation ?

$data = explode(",", trim(Input::get('Vehicle_Data')));  //exploding data
$rule  =  array(
$data[0] => 'required',
$data[1] => 'required',
$data[2] => 'required|email|unique:users'
              ) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
   {
    $messages = $validator->messages();
    return $messages;
    }
else
    {
    return 'ok'
    }

I just want to check the whether the $data[0] is required and should be unique

It works good when it is

'email' => 'required|email|unique:users'

But not working when it is

$data[2] => 'required|email|unique:users'

But i don't want to declare $data[2] into another variable and do it how can i do this without assigning data[2] to another variable

When ever i validate it is returning

Object {32: Array[1], 43: Array[1]}

in the console

Upvotes: 2

Views: 4588

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

It's probably not the best idea to do it the way you're trying, but here is how you achieve what you want:

$data = explode(",", trim(Input::get('Vehicle_Data')));  //exploding data

$rules = array(
   'required',
   'required',
   'required|email|unique:users,email'
);

$data will be simple array with numeric keys, so the $rules array should be just the same and it will work.


edit: as per comment, Validator::make is capable of 1 set custom messages, 2 set custom attributes. So for you the latter is the way to go:

$messages = []; // no need to specify that, unless you'd like
$attributes = ['id', 'name', 'email', ...]; // use your actual fields here

$validator = Validator::make($data, $rules, $messages, $attributes);

// then the messages will use $attributes array, so will show:
'The name has already been taken'
'The email field is required'

// instead of:
'The 1 has already been taken'
'The 2 field is required'

Upvotes: 2

Related Questions