phpsqllaravelmodel

Using Laravel Raw Query with Placeholder


I have this query in one of my Laravel models:

 class Webmasters {
      public static function webmasters($filt, $cat) {
         $top_pages = DB::table('web.tools')
                ->where('filter',$filt)
                ->where('category', $cat)
                ->limit(20)->get();
         return $top_pages;
}

The variables $filt and $cat are passed on as parameters from the controller.

I would like to use a query like this:

 class Webmaster {
      public static function webmasters($filt, $cat) {
         $top_pages = DB::select(DB::raw("SELECT *
                                         FROM web.tools
                                         WHERE filter = $filt
                                         WHERE category = $cat
                                         LIMIT 20"));
          return $top_pages;
       }
 }

However, I do not now how to use these placeholders on the second query. The first one works like a charm, but the second one gives me an sql error because of the placeholders $filt and $cat.


Solution

  • You can pass an array of parameters to bind to the select.

     class Webmaster {
          public static function webmasters($filt, $cat) {
             $top_pages = DB::select(DB::raw("SELECT *
                                             FROM web.tools
                                             WHERE filter = :filter
                                             AND category = :category
                                             LIMIT 20"), [
                                                 ':filter' => $filt,
                                                 ':category' => $cat
                                             ]);
              return $top_pages;
           }
     }