dpz90118 2019-04-17 04:47
浏览 59
已采纳

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

I have write code of search bar in laravel, I am doing pagination manually, but my search function is not working,

here is my code of view file

<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>

My Controller File Is

//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");
    }
}

and route is

Route::get('search-department', 'DepartmentController@search');
  • 写回答

1条回答 默认 最新

  • dtqu72830 2019-04-17 10:47
    关注

    I think You should try this code.

    In view

    <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>
    

    And in Controller

    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");
    }
    

    Hope This will help you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里