Laravel返回带有“ IF”验证的空白页

时间:2019-10-11 14:59:20

标签: php laravel

我是laravel的新手,我正在尝试解决这个问题。我要进行验证,用户必须至少选择3个值才能继续。我尝试使用count($array),但是它不起作用,我知道我做错了什么,但是我什么也没做。当我尝试代码之前返回空白页

在我的onboarding.blade.php中,我有此表格

    <form action="{{ url('/onboarding') }}" method="POST">
    @csrf
      @foreach($categories as $category)
        <div class="radio-item">
       <!-- <input class="form control" name="category_id" value="{{$category->id}}" type="hidden"> -->
       <input type="checkbox" id="category_id" name="category_id[]" value="{{$category->id}}">
          <label for="name">{{ $category -> title }}</label>
        </div>
        @endforeach

        <div class="form-row">
          <div class="form-group col-md-12 text-center">
            <button type="submit">Proceed to Authors</button>
          </div>
        </div>
      </form>

在我的OnboardsController.php中,我有这个

public function categoryUser (Request $request)
{
    $category_id = request('category_id');

    if (count($category_id) >= 3) {
        $user = Auth::user();
        $user->categories()->attach($request->input('category_id'));
        return redirect ( route ('onboarding_author')); 
    }
}

3 个答案:

答案 0 :(得分:0)

如果您的条件不正确怎么办!你不写。因此,将您的return语句移至if条件之外

public function categoryUser (Request $request)
{
    $category_id = request('category_id');

    if (count($category_id) >= 3) {
        $user = Auth::user();
        $user->categories()->attach($request->input('category_id'));
    }
    return redirect ( route ('onboarding_author'));
}

答案 1 :(得分:0)

在旁注中,您可以根据需要实际使用验证器。您可以使用如下规则:

WITH w AS ( SELECT territory FROM main_s LIMIT 3000 )
    SELECT COUNT(*)
        FROM w AS x1
        JOIN w AS x2
        GROUP BY x1.territory;

您可以使用Request对象进行快速验证:

'category_id' => 'array|min:3',
'category_id.*' => 'integer',

如果验证失败,将导致重定向回。

Laravel 6.x Docs - Validation - Available Rules - array

Laravel 6.x Docs - Validation - Available Rules - min

Laravel 6.x Docs - Validation - Quick Start - Writing the Validation Logic

答案 2 :(得分:0)

我认为lagbox的解决方案是正确的,但是如果您不想直接重定向用户,则可以使用以下方法手动重定向他:

if ($validator->fails()) {
   // Validation Fails Here...
   return redirect()->back()->withErrors($validator)->withInput();
}