如何在laravel中使用搜索功能?

时间:2019-04-17 04:47:03

标签: php laravel mongodb search

我在laravel中编写了搜索栏代码,我正在手动进行分页,但是我的搜索功能无法正常工作,

这是我的查看文件代码

<form action="{{url('search-department')}}" method="GET" role="search">
    <div class="form-group">
        <input type="text" class="form-control" name="q" placeholder="Search Department">
    </div>
</form>

我的控制器文件是

//Code For Insert record in collection
public function storeDepartment(Request $request)
{
    $department = new Department();
    $department->createdBy = $request->get('createdBy');
    $department->nameOfDepartment = $request->get('nameOfDepartment');
    $department->save();

    return redirect('list-department')->with('Success', 'Department Added Successfully!');
}

//Code For Seach
public function search(Request $request)
{
    $q = Input::get('q');

    if ($q != '') {
        $listOfDepartment = Department::where('nameOfDepartment', 'like', '%' . $q . '%')
            ->orwhere('createdBy', 'like', '%' . $q . '%')
            ->paginate(2);

        if (count($listOfDepartment) > 0) {
            return view('pages.department')->withData($listOfDepartment);
        }
        // return view('pages.department')->withMessage("No Data Found");
    }
}

路线是

Route::get('search-department', 'DepartmentController@search');

1 个答案:

答案 0 :(得分:0)

我认为您应该尝试使用此代码。

可见

<form role="search" method="GET">
    <div class="form-group">
        <input type="hidden" name="_token" value="{{csrf_token()}}">
        <input type="text" class="form-control" name="q" placeholder="Search Department">
    </div>
</form>

在控制器中

public function search(Request $request)
{
    $listOfDepartment = Department::select('*');

    if(isset($request->q) && !empty($request->q))
    {
        $q = $request->q;
        $listOfDepartment = $listOfDepartment->where('nameOfDepartment', 'like', '%' . $q . '%');
        $listOfDepartment = $listOfDepartment->orWhere('createdBy', 'like', '%' . $q . '%');
    }

    $listOfDepartment = $listOfDepartment->->paginate(2);

    if (count($listOfDepartment) > 0) {
        return view('pages.department')->withData($listOfDepartment);
    }
    // return view('pages.department')->withMessage("No Data Found");
}

希望这会对您有所帮助。