Nine3KiD
Nine3KiD

Reputation: 743

How can I pass my search keyword to my Controller?

I'm learning laravel 5.4 and i'm doing a sample project. In that I need to do a search from my DB. Below i have attached a screenshot of my interface.

enter image description here

As you can see in the searchbox i have given i need to search "malabe". And i need to get results for that. i have implemented Controller and needed views too. below i have attached my controller

class SearchController extends Controller
{
    //search controller
    public function search($keydown){
        $searchDetails = DB::table('van_Services')
            ->where('vs_RouteTo','like','%'.$keydown.'%')
            ->orwhere('vs_RouteFrom','like','%'.$keydown.'%')
            ->orwhere('vs_Description','like','%'.$keydown.'%')
            ->orderBy('created_at', 'DESC')
            ->paginate(12);

        return view('search.search', compact('searchDetails'));
    }
}

route code

Route::get('/search/{key}','SearchController@search');

here is the div of my search box code,

<div class="col-xs-6 col-sm-2 col-md-2">
    <div class="search_box pull-right">
           {{--Search Button--}}
           <input type="text" name="search" id="search" laceholder="Search"/>
    </div>
</div> 

My route and code works if i do the url manual,

enter image description here

my problem is how can i make my search box work? any tutorials or tips?

Upvotes: 0

Views: 316

Answers (2)

Vandolph Reyes
Vandolph Reyes

Reputation: 620

My route and code works if i do the url manual,

I assume it's already working and redirection is just your problem. Just simply use JS/jQuery.

// when ENTER is pressed
$(document).keypress(function (e) {
   if (e.which == 13) {
       e.preventDefault();

       window.location = APP_URL + "/search/" + $('#search').val();
   }
 });

Goodluck.

Upvotes: 1

Mgorunuch
Mgorunuch

Reputation: 686

1. If you really need to use URL link.

JS solution is:

// q => Your search word
function redirectSearch(q) {
  location.href = '/search/'+q;
}

pass search field value to this function and page redirect automatically.

.

2. You can send GET params to controller.

Front code:

<div class="col-xs-6 col-sm-2 col-md-2">
  <div class="search_box pull-right">
    <form action="/search" method="GET">
      {{--Search Button--}}
      <input type="text" name="search" id="search" placeholder="Search"/>
    </form>
</div>

Controller code:

public function search(Request $request){
  $search = $request->search;
  ... Your code ...
}

If you use method with request don`t forget about

use Illuminate\Http\Request;

Route:

Route::get('/search','SearchController@search');

Upvotes: 1

Related Questions