• Reading time ~ 1 min
  • 30.03.2023

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 products
Product::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

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297