简体   繁体   English

Laravel 5 Blade模板未定义变量

[英]Laravel 5 blade template Undefined variable

I did a search and I want to display the result, but I cannot convey the variable to the view, although I specify it in the controller. 我进行了搜索,并且想要显示结果,但是尽管我在控制器中指定了变量,但无法将变量传达给视图。

My piece of view code: 我的视图代码:

<div class="search col-md-6">
    <p>
        Найти сотрудника по id
    </p>
    <form action="{{route('searchID')}}" class="search-id" method="GET">
        <div class="row">
            <div class="col-xs-10">
                <div class="form-group">
                    <input class="form-control" name="id" required="" type="text" value="{{ old('id') }}">
                    </input>
                </div>
            </div>
            <div class="col-xs-2">
                <div class="form-group">
                    <input class="btn btn-info" type="submit" value="Искать">
                    </input>
                </div>
            </div>
        </div>
        {{$result}}
    </form>
    <div>
    </div>
</div>

my route: 我的路线:

 Route::match(['get', 'post'], 'searchID', 'SearchController@indexID')->name('searchID');

my method in the controller: 我在控制器中的方法:

public function indexID(Request $request, View $view)
{
    //$message= "Сотрудник не найден";
    $id = $request->input('id');
    dump($id);
    $result = Staff::where('public_id', $id)->get();

    if ($result == null) {
        //dump($message);
        return redirect()->back()->withInput($id);
    } else {
        dump($result);
        return view('addworker')->with('result', $result);
    }
}

But I constantly get an error: Undefined variable: result 但我不断收到一个错误: 未定义的变量:结果

I tried: 我试过了:

return view('addworker')->with($result);

and

return view('addworker',$result);

and

return view('addworker', ['result', $result]);

None of this helped me, I don't know what to do anymore 这些都没有帮助我,我不知道该怎么办

How to make the template access this variable only after the controller has been processed? 仅在处理完控制器后,如何使模板访问此变量?

You can use compact for the same, 您可以使用紧凑型

return view('addworker', compact('result'));

compact — Create array containing variables and their values compact —创建包含变量及其值的数组

我希望这能帮到您

return view('addworker', ['result' => $result]);

You used the wrong syntax to send your variable to your view, there is a lot os ways to do that: 您使用了错误的语法将变量发送到视图,有很多方法可以这样做:

You could use the compact function: 您可以使用紧凑功能:

return view('addworker', compact('result'));

You could use the with() method: 您可以使用with()方法:

return view('addworker')->with('result', $result);

Or: 要么:

return view('addworker', ['result' => $result]);

You could also check the official documentation: click here 您也可以查看官方文档: 单击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM