Run raw query in Laravel.

2024-04-20 06:56:42 Rahul Laravel

How to use raw queries in Laravel?

Laravel is an awesome framework. It provides you flexibilities for development. Once you realize it’s cool features, you will just love the framework. One such cool feature us using raw queries. You might wonder what’s new here. But this is really helpful when you want to use raw expressions like aggregate functions. The queries can be executed using DB::Raw method. Let’s have a look at the following example where we want to find out the number of users grouped by their status.

$users = DB::table('users')
      ->select(DB::raw('count(*) as user_count, status'))
      ->where('status', '', 1)

These expressions will be injected into the query as strings, so be careful not to create any SQL injection points!

This post is submitted by one of our members. You may submit a new post here.

Related Tricks