laravel验证用户功能

时间:2017-06-13 06:15:44

标签: php laravel validation unique

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();

我需要将cameraMac转换为主键以存储在db中。如何在验证规则transform()中使用函数'nullable|unique:cloud_cameras,id|size:6'。这就是说,如何在验证过程中调用此函数。

5 个答案:

答案 0 :(得分:3)

如果您需要以某种方式转换输入数据,可以使用merge方法:

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

作为个人偏好,我会在控制器方法中键入-hint Illuminate\Http\Request $request然后

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

答案 1 :(得分:2)

我考虑PH-Tree

中间件将执行转换并在击中控制器之前将结果合并回请求。

class TransformId {
    public function handle(Request $request, Closure $next) {
        // shout out to @alepeino
        $request->merge(['cameraMac' => transform($request->cameraMac)]);

        return $next($request);
    }
}

答案 2 :(得分:1)

您是否真的想要将字段cameraMac作为(或多或少)主键可以为空?

您还应使用int验证来使用size验证 unique validation的第三个参数是except,它将忽略给定的ID。

您在控制器中的验证可能如下所示

$except_id = $request->input('cameraMac', null);

$this->validate($request, [
  'cameraMac' => 'nullable|unique:cloud_cameras,id,'.$except_id.'|int|size:6'
]);

One example如何在视图中显示您的验证错误

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

答案 3 :(得分:1)

现在我首先转换输入数据,然后以下面的方式验证它。

但我正在寻找在验证中调用此功能的方法。

$data = Input::all();
$data['cameraMac'] = transform($data['cameraMac']);
$rules = array(
  'id' => 'required|unique:cloud_printers,id|size:6',
  'cameraMac' => 'unique:cloud_cameras,id|size:6',
);
$validator = Validator::make($data, $rules);
if ($validator->fails())
  return Redirect::back()->withInput()->withErrors($validator);

答案 4 :(得分:1)

您可以定义custom validation rule

char input;
displayWellDoneMenu();
scanf("%c", &input);

while (input != '1' || input != '2')
{
    printf("You must select 1 or 2!\n");
    displayWellDoneMenu();
    scanf("%c", &input);
    rewind(stdin);
    system("cls");
}

switch (input)
{
    case'1':
        additionIntermediate();
        break;
    case '2':
        main();
        break;
}

然后像往常一样在请求中使用新规则:

Validator::extend('transformUpper', function ($attribute, $value, $parameters, $validator) {
   return strtoupper($value);
});