How to do raw query in Laravel


Besides the standard methods for database query that are available on laravel, you also have an option to do raw query, in this article i will show you how to do raw database query in laravel.

The most common way to do raw query in laravel is calling the DB::raw() method, here's an example using DB::raw on a select statement.
$users = DB::table('users')
                     ->select(DB::raw('count(id) as total, status as user_status'))
                     ->get();

Another example:
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

There is also whereRaw() statement if you want to do raw query in where statement, here's an example:
$users = DB::table('users') ->whereRaw("email like '%yahoo%'") ->get();

Lastly, you can also do raw query on a having clause, in laravel there is the havingRaw() statement that you can use.
$users = DB::table('users')
      ->havingRaw('COUNT(*) > 1')
      ->get();


EmoticonEmoticon