[英]Search Food Items in laravel
我的视图中有一个搜索框,我想从数据库中搜索食物。 我对搜索框的看法是:
<div class="field" id="searchform">
<input type="text" id="searchterm" placeholder="e.g mutton
karahi,pizza..." />
<button type="button" id="search"
onclick="window.location='http://localhost:8000/search'">Find Food!</button>
</div>
我的餐桌上有如下字段:
现在我想按名称搜索食物,我该怎么做?请帮助我.laravel我是新手,我正在使用laravel 5.2。
假设您的表名是foods
,则可以使用控制器中的Eloquent或DB Facade来实现。
public function search(){
$foodName = Input::get('food_name'');
$foods = Food::where('FoodName', $foodName)->get();
return $foods;
}
这是最简单的版本。 希望对您有所帮助。
在Laravel搜索
正如您提到的,您有一张桌子说food
我们将在您的app
文件夹中生成一个模型Food.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Food extends Model {
use SoftDeletes;
protected $table = 'food';
protected $fillable = ['id','name','description','image'];
protected $dates = ['deleted_at'];
}
克里特搜索控制器
php artisan make:controller SearchController
在Controller内部编写逻辑以根据食物名称检索模型记录
public function search(Request $request){ $foods = Food::where('name','%LIKE%',$request->input('q'))->get(); return view('search')->with(['foods'=>$foods]); }
现在,我们返回模态进行查看。 您可以在控制器中或视图中使用dd($foods)
来检查结果
在搜索表单视图中,对SearchController进行操作
{{Form::open(array('action' => 'SearchController@search','method'=>'post','name'=>'mini_search','id'=>'mini_search','role'=>'form')) }}
\n\n
\n\n<div class="field" > <input type="text" id="searchterm" placeholder="eg mutton karahi,pizza..." name="q" /> <button type="submit" id="search" >Find Food!</button> </div> {{Form::close()}}
最后,我们还需要一个视图来显示结果,因此创建一个文件search.blade.php并显示结果。 https://laravel.com/docs/5.2/views#passing-data-to-views
<ul> @foreach($foods as $food) <li>{{$food->name}}</li> @endforeach </ul></pre>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.