Laravel groupByRaw query Example; In this tutorial we are going to share how to use groupByRaw() query in laravel app. Here we have easy and simple way to explained laravel groupByRaw eloquent query method.
The groupByRaw method may be used to provide a raw string as the value of the group by clause. Let’s see the below example to get records uinsing group by raw query.
Example 1:
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users = User::select('city')
->groupByRaw('state')
->get();
dd($users);
}
}
Example 2:
$results = User::select(\DB::raw('YEAR(birth_date) as year, COUNT(id) as amount'))
->groupBy(\DB::raw('YEAR(birth_date)'))
->get();