Laravel Query Builder Package: Configurable Query Construction without IF‑ELSE

This article introduces the Laravel‑query‑builder package, explaining how to replace complex IF‑ELSE query logic with a configuration‑driven approach, and provides installation steps, usage examples, and code snippets for building flexible SQL queries in Laravel applications.

php Courses
php Courses
php Courses
Laravel Query Builder Package: Configurable Query Construction without IF‑ELSE

Many Laravel projects suffer from hard‑to‑maintain query code that relies on numerous if statements to apply different where clauses based on request parameters.

The solution is to configure query conditions externally and let a service package construct the queries automatically, resulting in cleaner and more elegant code.

Package Overview

The laravel-query-builder package reads a configuration array and builds the appropriate query conditions for Laravel models.

Installation composer require zyimm/laravelquery-builder Requirements

{
  "require": {
    "php": ">=7.0",
    "fideloper/proxy": "^4.0",
    "laravel/framework": ">=5.5"
  }
}

Usage Example

/**
 * Supported operators:
 * '=', '<>', '>', '>=', '<', '<=', 'like', 'full_like',
 * 'in', 'not_in', 'between', 'not_between'
 */
use Illuminate\Support\Facades\DB;
use zyimm\query\build\QueryWhere;

$build = app('QueryWhere');
$data = [
    'log_id'   => 20,
    'user_id'  => 'zyimm',
    'user_name'=> "zyimm,12"
];

$condition = [
    '=' => ['log_id'],
    'not_in' => ['user_id'],
    'between' => ['user_name'],
    'full_like' => ['user_id'],
    '<>' => ['user_id'],
    '>' => ['user_id']
];

DB::enableQueryLog();
\App\Models\Log::query()
    ->where(function ($query) use ($build, $data, $condition) {
        $build->buildQueryWhere($data, $condition, $query);
    })
    ->get();

dd(DB::getQueryLog());

The generated SQL query log is shown in the accompanying screenshot.

Tips 'in','not_in','between','not_between' support both arrays and delimited strings (comma or dot).

This simple approach makes the code more maintainable and elegant.

Project repository: https://github.com/zyimm/laravel-query-builder

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendsqlConfigurationPHPquery builder
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.