Ali.Ghzd
Ali.Ghzd

Reputation: 319

how can I send a textbox value as a search item to controller in laravel?

I have a words table and I want to keep a search form in my index view to search intended word.

This is function that I have wrote for search in controller.

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

and This is my form code in view

{!! 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() !!}

Now I want to know how can I send text value as $id parameter to search function and should method be 'GET' or ' POST'?

Upvotes: 1

Views: 795

Answers (1)

Yogesh Patil
Yogesh Patil

Reputation: 51

You can Use Get method for filter like operation you just have to send request

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

}

In blade file you have to do this for filtering purpose

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

Upvotes: 1

Related Questions