【问题标题】:laravel 5 validation using request not working - Undefined variable error使用请求的laravel 5验证不起作用 - 未定义的变量错误
【发布时间】:2016-01-20 22:37:26
【问题描述】:

我正在使用 Laravel 5.2,我有表单并且想要插入带有验证的字段。我在 Requests 文件夹下创建了 createQuranRequest 并尝试回显验证错误,但出现以下错误

a19890dff92858726bf2b1048815af329d53d3b6.php 第 6 行中的 ErrorException: 未定义的变量:错误(查看: /Applications/MAMP/htdocs/quran/resources/views/pages/quranForm.blade.php) (查看:/Applications/MAMP/htdocs/quran/resources/views/pages /quranForm.blade.php)

我试图吐出错误的 quranForm.blade.php 代码

<div class="form-group">
  {!!Form::label('title','Surah Title:')!!}    
  {!!Form::text('title',null,['class' => 'form-control'])!!} 
  <span class="help-block">{{$errors->first('title') }}</span>
 </div>

 <div class="form-group">
   {!!Form::label('lyrics','Surah Lyrics:')!!}       
   {!!Form::textarea('lyrics',null,['class' => 'form-control'])!!}  
 </div>

 <div class="form-group">
   {!!Form::submit('Add Surah',['class' => 'btn btn-primary'])!!}
 </div>

我的 createQuranRequest 文件

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class createQuranRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'lyrics' => 'required'
        ];
    }
}

我的控制器文件

public function store(createQuranRequest $request, quran $quran){ 
  $quran->create($request->all());
  return redirect('quran');
}

我试过下面的代码

@if (Session::get('errors'))
  <ul>
    @foreach ($errors->all() as $error)
      <li>{ { $error } }</li>
    @endforeach
  </ul>
@endif   

它删除了异常错误,但不显示错误。

【问题讨论】:

    标签: php forms validation laravel-5 request


    【解决方案1】:

    laravel 文档说 $errors 变量由 Illuminate\View\Middleware\ShareErrorsFromSession 中间件绑定到视图,该中间件由 web 中间件组提供。

    所以你必须更新位于 app/http/routes.php 中的路由文件

    Route::group(['middleware' => ['web']], function () 
    {
        //this route will use the middleware of the 'web' group, so session and auth will work here         
        Route::post('/your-endpoint','MyController@store');       
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2020-12-10
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2015-12-24
      • 2019-02-18
      相关资源
      最近更新 更多