Sazrit Mustafa
Sazrit Mustafa

Reputation: 145

search function in Laravel

I'm trying to make a search function in laravel. But it is showing:

"undefined variable:q"

though I defined the variable. I am not getting any clue where I made mistake. I need help on that.

Here is my controller code:

public function postSearch(Request $request)
{
         $q = $request->input('q');
    $products = DB::table('products')
                        ->join('product_categories', function ($join) {
                            $join->on('category_id', '=', 'product_categories.id')
                                ->where('name','LIKE','%'.$q.'%')->orWhere('category_name','LIKE','%'.$q.'%');
                            })->get();
    if(count($products) > 0)
        return view('search')->withDetails($products)->withQuery ( $q );
    else return view ('search')->withMessage('No Details found. Try to search again !');
}

Here is my route:

Route::post('/search',[
   'uses' => 'HomeController@postSearch',
   'as' => 'search'
]);`

here is my view form:

<form action="{{ route('search') }}" method="post" role="search">
    {{ csrf_field() }}
    <div class="input-group">
        <input type="text" class="form-control" name="q" placeholder="Search    products"> 
        <span class="glyphicon glyphicon-search"></span>
            <button type="submit" class="btn-btn-primary">Submit</button>
        </span>
    </div>
</form>

Upvotes: 1

Views: 1297

Answers (1)

zaidysf
zaidysf

Reputation: 502

Change the following code:

->join('product_categories', function ($join) { 

to this code:

->join('product_categories', function ($join) use ($q) {

Note: you cannot use external variable inside it before you declare the variable to pass it.

Upvotes: 1

Related Questions