猿问

如何在视图文件 Laravel 5.4 中使用计数行数和打印值?

app/http/controller/FirstController.php


public function delhi_property()

{

    $sql = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();

    return view('index',['results'=>$sql]);

}

资源/视图/index.blade.php


<h3>({{ $results->count() }}) Properties</h3>

路线/ web.php


Route::get('/','FirstController@delhi_property');

我是laravel 5.4的新手在这里,我在做什么我只是像上面提到的那样运行查询Controller并想在我的视图文件中打印行数但是当我检查它时显示一个错误,即


Undefined variable: result (View: D:\xampp\htdocs\real_estate\resources\views\index.blade.php)


那么我该如何解决这个问题呢?请帮我。


摇曳的蔷薇
浏览 132回答 3
3回答

潇湘沐

您将查询结果作为“results”返回,因此在视图中您需要将其作为“$results”访问。在错误中它说未定义的变量结果。里面没有“s”。所以参考错误返回的代码行,检查变量命名是否正确。

阿晨1998

在控制器中:public function delhi_property(){&nbsp; &nbsp; $data = DB::table('property')->where('city', 'Delhi')->orWhere('city', 'New Delhi')->get();&nbsp; &nbsp; return view('index', compact('data'));}在刀片文件中:<h3>( {{ $data->count() }} ) Properties</h3>或者<h3>( {{&nbsp; count($data) }} ) Properties</h3>

哆啦的时光机

I am modifying your query a bit, will achieve the same result efficiently&nbsp; &nbsp; public function delhi_property()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $cityResults = DB::table('property')->whereIn('city', ['Delhi','New Delhi'])->get();&nbsp; &nbsp; &nbsp; &nbsp; return view('index',compact('cityResults'));&nbsp; &nbsp; }在您看来,您可以按如下方式访问计数:<h3>{{ $cityResults->count() }} Properties</h3>
随时随地看视频慕课网APP
我要回答