在Laravel中进行搜索功能

时间:2019-09-16 15:54:45

标签: php laravel

我想进行搜索,将得到我们在栏中键入的结果。就像当我键入“国家”时,它应该得到此搜索的结果。 我在控制器中创建了一个搜索功能,还创建了它的路由并为其创建了一个视图文件。我正在分享我的工作代码,请帮助我哪里出问题了。上帝保佑你。 laravel中的新功能。谢谢。

//HERE IS MY VIEW FILE FOR SEARCH RESULT.
@extends('footer')
@extends('header')
<html>
    <head>
        <title>
            Search|Result 
        </title>

        <link rel="stylesheet" type="text/css" href="{{ asset('public/css/style.css') }}">
        <link rel="stylesheet" type="text/css" href="{{ asset('public/css/bootstrap.css') }}">
        <script type="text/javascript" src="{{ asset('public/js/jQuery.js') }}"></script>
        <script type="text/javascript" src="{{ asset('public/js/javascript.js') }}"></script>
        <script src="https://kit.fontawesome.com/a076d05399.js"></script>

    </head>
    <body>


<div class="container">
    @if(isset($user))
        <p> The Search results for your query <b></b> are :</p>
    <h2>Sample User details</h2>
    <table border="1">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            @foreach($user as $value)
            <tr>
                <td>{{$value->name}}</td>
                <td>{{$value->email}}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
    @endif
</div>
 </body>
</html>

//HERE IS MY CONTROLLER CODE.

public function Search(Request $request)
        {

           $q = Input::get ( 'q' );
           $user = DB::table('student')->where('name','LIKE','%'.$q.'%')
           ->orWhere ( 'email', 'LIKE', '%' . $q . '%' )->get();
           if(count($user) > 0)
           return view('search_result')->withDetails($user)->withQuery ( $q );
           else 
            return redirect()->route('std_view')->with('No Details found. Try to search again !');
        }

//HERE IS MY SEARCH BAR CODE 

<form action="search/result" method="get" role="search" class="form-inline">
    {{ csrf_field() }}
      <input class="form-control form-control-sm ml-3 w-75" type="text" name="q" placeholder="Search"
    aria-label="Search">
 </form>

//HERE IS MY ROUTE

Route::get('search/result','StudInsertController@Search');

1 个答案:

答案 0 :(得分:0)

嘿,告诉我们您的问题是什么,为了简单起见,您可以使用两件事

  1. 表单方法应为POST
  2. 作为回报,您可以使用紧凑型

    返回视图('search_result',compact('user','q'));