Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel validate with user function

blade.php

......
<tr>
  <td>{{ Form::label('cameraMac', 'Mac: ') }}</td>
  <td>{{ Form::text('cameraMac')}}</td>
</tr>
......

controller.php

$data = Input::all();
function transform($cameraMac) {
  return strtoupper($cameraMac);
}

//validation here

$user = User::find($data['user_id']);

if($data["cameraMac"])
{
    $user->camera_id = transform($data["cameraMac"]);
    Cloud_camera::create(['id' => transform($data["cameraMac"]), 'user_id' => $user->id]);
}

$user->save();

I need to transform the cameraMac to primary key to store in db. How can I use function transform() in the validation rule 'nullable|unique:cloud_cameras,id|size:6'. That's to say, how can I call this function in the validation process.

like image 939
LF00 Avatar asked Jun 13 '17 06:06

LF00


1 Answers

If you need to somehow transform the input data you can use the merge method:

Input::merge(['cameraMac' => transform(Input::get('cameraMac')]);
$this->validate(Input::getFacadeRoot(), [
    'cameraMac' => 'nullable|unique:cloud_cameras,id|size:6'
]);

As a personal preference I would instead type-hint Illuminate\Http\Request $request in the controller method and then

$request->merge(['cameraMac' => transform($request->cameraMac)]);
$this->validate($request, ['cameraMac' => 'nullable|unique:cloud_cameras,id|size:6'
]);
like image 81
alepeino Avatar answered Oct 02 '22 00:10

alepeino