Creating search functionality with Laravel 4

Posted by Mitch Glenn on Stack Overflow See other posts from Stack Overflow or by Mitch Glenn
Published on 2013-10-26T21:39:13Z Indexed on 2013/10/26 21:54 UTC
Read the original article Hit count: 314

Filed under:
|
|

I am trying to create a way for users to search through all the products on a website. When they search for "burton snowboards", I only want the snowboards with the brand burton to appear in the results. But if they searched only "burton", then all products with the brand burton should appear.

This is what I have attempted to write but isn't working for multiple reasons.

Controller:

 public function search(){
    $input = Input::all();

    $v= Validator::make($input, Product::$rules);

    if($v->passes())
    {

        $searchTerms = explode(' ', $input);
        $searchTermBits = array();
        foreach ($searchTerms as $term) {
            $term = trim($term);
            if (!empty($term)){
                $searchTermBits[] = "search LIKE '%$term%'";
            }
        }
        $result = DB::table('products')
        ->select('*')
        ->whereRaw(". implode(' AND ', $searchTermBits) . ")
        ->get();

        return View::make('layouts/search', compact('result')); 
    }
    return Redirect::route('/');    
}

I am trying to recreate the first solution given for this stackoverflow.com problem

The first problem I have identified is that i'm trying to explode the $input, but it's already an array. So i'm not sure how to go about fixing that. And the way I have written the ->whereRaw(". implode(' AND ', $searchTermBits) . "), i'm sure isn't correct. I'm not sure how to fix these problems though, any insights or solutions will be greatly appreciated.

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql