2016-04-06 123 views
1

我想驗證我的Laravel應用程序中的複選框。複選框的HTML名稱和值是從我的數據庫生成的,我正在做一個循環來顯示所有的框。如何執行驗證規則,以便至少檢查一個框或要求?這些是來自我的刀片文件的相關視圖代碼和來自我的控制器的方法。驗證多個複選框laravel 5.2

//Snippet from create-user.blade.php 
<div class='form-group'> 
    @foreach ($roles as $role) //$role variable gets its data from the db 
    {{ Form::label('role', $role->display_name) }} 
    {{ Form::checkbox($role->name, $role->id) }} 
    @endforeach 
</div> 

//Snippet from UserController.php 
public function addUser(Request $request) 
{ 

    $this->validate($request, [ 
     'name'=>'required|max:120|alpha_dash', 
     'email'=>'required|email|unique:users', 
     $role->name =>'required', //This line results in 'Undefined variable: role' 
     'password'=>'required|min:4', 
     'password_confirmation'=>'required|min:4'] 
    ); 
    $email = $request['email']; 
    $name = $request['name']; 
    $password = bcrypt($request['password']); 
    $user = new User(); 
    $user->email = $email; 
    $user->name = $name; 
    $user->password = $password; 
    $user->save(); 

    return redirect()->route('account'); 
} 

在驗證數組中,我通過了什麼來代替$role->name? 謝謝

+0

試着通過'Log :: error()'方法看到'$ request-> all()'的輸出......你會看到基於你的複選框名稱,將有多個項目在數組..你需要循環該數組並分別驗證每個字段。 – Rash

回答

0

除了創建角色名稱複選框之外,還可以使用靜態名稱創建複選框,如roles[]。我修改了你的代碼,看看。還添加角色附加到用戶(我假設您已在User模型中有roles關係)。

//Snippet from create-user.blade.php 
<div class='form-group'> 
    @foreach ($roles as $role) //$role variable gets its data from the db 
    {{ Form::label('roles', $role->display_name) }} 
    {{ Form::checkbox('roles[]', $role->id) }} 
    @endforeach 
</div> 

//Snippet from UserController.php 
public function addUser(Request $request) 
{ 
    $this->validate($request, [ 
      'name'     => 'required|max:120|alpha_dash', 
      'email'     => 'required|email|unique:users', 
      'roles'     => 'required', 
      'password'    => 'required|min:4', 
      'password_confirmation' => 'required|min:4' 
     ] 
    ); 
    $email   = $request['email']; 
    $name   = $request['name']; 
    $password  = bcrypt($request['password']); 
    $user   = new User(); 
    $user->email = $email; 
    $user->name  = $name; 
    $user->password = $password; 
    $user->save(); 

    //attach roles 
    $user->roles()->sync($request->input('roles',[])); 

    return redirect()->route('account'); 
} 
+0

謝謝你的答案,部分工作。現在在提交表單後,即使我選擇了一個,也會自動檢查這兩個複選框。有沒有辦法解決這個問題? –

+0

對不起,在腳本中留下了一個小錯誤:'{{Form :: checkbox('roles',$ role-> id)}}''應該是'{{Form :: checkbox('roles],$ role- > id)}}'。然後你會發布數組,如果角色ID到控制器,它應該按照你想要的工作。 –