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.
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
<code>composer require zyimm/laravelquery-builder</code>Requirements
<code>{
"require": {
"php": ">=7.0",
"fideloper/proxy": "^4.0",
"laravel/framework": ">=5.5"
}
}</code>Usage Example
<code>/**
* 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());</code>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
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.