Laravel在视图中给我未定义的变量错误异常


Laravel is giving me Undefined variable Error Exception in views

我有这样的代码:

public function lookupTransflow()
{
    //redirect back with data...perform a count on the data n display (1 fills the forms 2 for selct)
    $input=Input::get('search');
    $schools =  Transflow::where('school', 'LIKE', '%'.$input.'%')->get();
    return Redirect::route('search')->with('schools',$schools);
}

我想把结果传递给这个视图:

 @if(Session::has('schools'))
            @foreach($schools as $school)
        <a href="#" class="list-group-item">{{$school->school}}</a>
           @endforeach
       @endif

我做错了什么

您似乎混淆了传递给视图的数据和传递给Redirect实例的数据-在请求之间闪现-即使您在视图中正确检查它。

我最好的猜测没有看到你如何处理实际的search路由,是你需要从会话中获得schools集合,以便使用它。

@if(Session::has('schools'))
    // $schools is not set, but you can get it directly from Session
    @foreach(Session::get('schools') as $school)
        <a href="#" class="list-group-item">{{$school->school}}</a>
    @endforeach
@endif

尽管,正如Martin在评论中指出的那样,您可能希望在实际进入视图之前执行此操作。例如在您的search路由中:

Route::get('search', function()
{
    $schools = array();
    if (Session::has('schools'))
    {
        $schools = Session::get('schools');
    }
    return View::make('search', compact('schools'));
});

如果你遵循第二个建议,$schools将始终被设置,你不必在视图中使用Session类。