【问题标题】:how can I send a textbox value as a search item to controller in laravel?如何将文本框值作为搜索项发送到 laravel 中的控制器?
【发布时间】:2021-07-18 07:33:21
【问题描述】:

我有一个单词表,我想在我的索引视图中保留一个搜索表单来搜索想要的单词。

这是我在控制器中编写的用于搜索的函数。

public function search(string $id){                
    if($id!="")
    {
        $terms = Terms::query()
        ->where('term', $id)           
        ->get();

        if(count($terms)==0)
        {
            $terms = Terms::query()
            ->where('term', 'LIKE', "{$id}%")
            ->orWhere('term', 'LIKE', "%{$id}%")
            ->get();
        }
        if(count($terms)==0)
        {
            $terms = Terms::query()           
            ->orWhere('term', 'LIKE', "%{$id}%")
            ->get();
        }
    return view('admin/terms/search')->with('terms', $terms);
    }       
}

这是我的表单代码

{!! Form::open(['action' => 'App\Http\Controllers\TermsController@search', 'method' => 'GET']) !!}
<form class="bd-forms">
    
    <div class="form-group">
            {{ Form::label('word', 'Search word') }}
            {{ Form::text('word', '', ['class' => 'form-control', 'placeholder' => 'type word here']) }}
        @error('word')
            <div class=""
                style="padding-right:5px;margin-top:5px;margin-bottom:10px; color:red;font-size:12px;">


                the field is empty.

            </div>
        @enderror
    </div>          
    <div>
        {{ Form::submit('Search', ['class' => 'btn btn-primary']) }}
    </div>
</form>
{!! Form::close() !!}

现在我想知道如何将文本值作为$id 参数发送到搜索函数,方法应该是“GET”还是“POST”?

【问题讨论】:

    标签: php laravel forms


    【解决方案1】:

    您可以使用 Get 方法进行过滤操作,您只需发送请求即可

    public function search(Request $r){ 
    $filter=$r->query('id');               
    if(!empty($filter))
    {
        $terms = Terms::query()
        ->where('term', 'like', '%'.$filter.'%')           
        ->get();
    
       $terms->appends($request->all());
    }
    else
    {
        $terms = Terms::get();
    }
    return view('admin/terms/search')->with('terms', $terms);
    

    }

    在刀片文件中,您必须这样做以进行过滤

    <form class="form-inline justify-content-center" method="GET">
            <input type="text" class="form-control mr-2 text-center"  name="id" placeholder="term" value="{{$id}}">
          <button type="submit" >Search</button>
        </form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多