Replace Raw Query Calls With Laravel Query Expressions
Published on by Paul Redmond
The Query Expressions package for Laravel replaces any raw query calls with expressions. Instead of writing the following example from the readme:
// Instead of:User::query() ->when(isPostgreSQL(), fn ($query) => $query->selectRaw('coalesce("user", "admin") AS "value"')) ->when(isMySQL(), fn ($query) => $query->selectRaw('coalesce(`user`, `admin`) AS `value`'))
You could write something like the following using this package:
User::select( new Alias(new Coalesce(['user', 'admin']), 'count')); // More examples: // UPDATE user_quotas SET credits = credits - 15 WHERE id = 1985$quota->update([ 'credits' => new Subtract('credits', new Number(15)),]); // SELECT id, name, (price - discount) * 0.2 AS vat FROM productsProduct::select([ 'id', 'name', new Alias(new Multiply(new Subtract('price', 'discount'), Number(0.2)), 'vat')])->get();
Besides the terser code, why would you want to use something like this package? The readme describes how this package fits into your Laravel apps:
Laravel's database implementation provides a good way of working with multiple databases while abstracting away their inner workings...
However, when we want to use more database functionality than Laravel provides, we must fall back to raw SQL expressions and write database-specific code. The Query Expressions package builds on new features introduced in Laravel 10 to solve that problem.
At the time of writing, this package supports various expressions, such as:
- Values
- Aliases
- Arithmetic operators
- Bitwise operators
- Comparison and Logical operators
- Aggregate functions
- Conditional
If you'd like to learn more about this package, check out laravel-query-expressions on GitHub. You can install this package in your Laravel 10 project via composer:
composer require tpetry/laravel-query-expressions