PHPackages                             bytegourmet/laravel-conditional-expressions - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. bytegourmet/laravel-conditional-expressions

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

bytegourmet/laravel-conditional-expressions
===========================================

Fluent CASE WHEN expression builder for Laravel

1.0.2(3mo ago)022MITPHPPHP &gt;=8.2

Since Mar 9Pushed 3mo agoCompare

[ Source](https://github.com/ByteGourmet/laravel-conditional-expressions)[ Packagist](https://packagist.org/packages/bytegourmet/laravel-conditional-expressions)[ RSS](/packages/bytegourmet-laravel-conditional-expressions/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (3)Dependencies (5)Versions (4)Used By (0)

[![Cover](./assets/cover.png)](./assets/cover.png)

Laravel Conditional Expressions
===============================

[](#laravel-conditional-expressions)

A fluent CASE WHEN expression builder for Laravel that makes it easy to write complex conditional SQL expressions in your queries.

Features
--------

[](#features)

- 🎯 **Fluent API** - Chain methods for readable CASE expressions
- 🔄 **Nested CASE** - Support for nested CASE expressions
- 🛠️ **Complex Conditions** - Use `CaseBuilder` for complex WHERE conditions
- 📦 **Laravel Integration** - Works seamlessly with Eloquent and Query Builder
- 🔒 **Parameter Binding** - Automatic parameter binding for security
- 🎨 **Simple &amp; Searched CASE** - Support for both CASE types

Requirements
------------

[](#requirements)

- PHP &gt;= 8.2
- Laravel &gt;= 10.0

Installation
------------

[](#installation)

### Standard Installation

[](#standard-installation)

Install the package via Composer:

```
composer require bytegourmet/laravel-conditional-expressions
```

The package will automatically register its service provider.

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$users = User::query()
    ->select([
        'id',
        'name',
        CaseExpr::make()
            ->when('status', '=', 'active')
            ->then('Active User')
            ->when('status', '=', 'inactive')
            ->then('Inactive User')
            ->else('Unknown')
            ->as('status_label')
    ])
    ->get();
```

Usage
-----

[](#usage)

### Simple CASE Expression

[](#simple-case-expression)

A simple CASE expression compares a column against multiple values:

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$case = CaseExpr::simple('status')
    ->when('active')
    ->then('User is active')
    ->when('inactive')
    ->then('User is inactive')
    ->else('Unknown status')
    ->as('status_description');

// Generates: CASE `status` WHEN 'active' THEN 'User is active' WHEN 'inactive' THEN 'User is inactive' ELSE 'Unknown status' END AS `status_description`
```

### Searched CASE Expression

[](#searched-case-expression)

A searched CASE expression evaluates conditions (no column comparison):

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$case = CaseExpr::make()
    ->when('age', '>=', 18)
    ->then('Adult')
    ->when('age', '>=', 13)
    ->then('Teenager')
    ->else('Child')
    ->as('age_category');

// Generates: CASE WHEN `age` >= ? THEN ? WHEN `age` >= ? THEN ? ELSE ? END AS `age_category`
```

### Using in Queries

[](#using-in-queries)

#### With Eloquent Models

[](#with-eloquent-models)

```
use App\Models\User;
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$users = User::query()
    ->select([
        'id',
        'name',
        'email',
        CaseExpr::make()
            ->when('email_verified_at', '!=', null)
            ->then('Verified')
            ->else('Unverified')
            ->as('verification_status')
    ])
    ->get();
```

#### With Query Builder

[](#with-query-builder)

```
use Illuminate\Support\Facades\DB;
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$results = DB::table('orders')
    ->select([
        'id',
        'total',
        CaseExpr::make()
            ->when('total', '>', 1000)
            ->then('High Value')
            ->when('total', '>', 500)
            ->then('Medium Value')
            ->else('Low Value')
            ->as('order_category')
    ])
    ->get();
```

### Nested CASE Expressions

[](#nested-case-expressions)

You can nest CASE expressions for complex logic:

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$case = CaseExpr::make()
    ->when('phone_verified', '=', true)
    ->then(
        CaseExpr::make()
            ->when('email_verified', '=', true)
            ->then('Fully Verified')
            ->else('Phone Verified Only')
    )
    ->else('Unverified')
    ->as('verification_status');
```

### Complex Conditions with CaseBuilder

[](#complex-conditions-with-casebuilder)

For complex WHERE conditions in your CASE expressions, use `CaseBuilder`:

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$caseBuilder = CaseExpr::builder()
    ->where('status', 'active')
    ->where('email_verified_at', '!=', null)
    ->orWhere('phone_verified_at', '!=', null);

$case = CaseExpr::make()
    ->when($caseBuilder)
    ->then('Fully Verified')
    ->when('status', '=', 'pending')
    ->then('Pending Verification')
    ->else('Unverified')
    ->as('account_status');
```

#### Advanced CaseBuilder Usage

[](#advanced-casebuilder-usage)

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$caseBuilder = CaseExpr::builder()
    ->where('a', 1)
    ->where('b', '>', 2)
    ->orWhere([
        'c' => 3,
        'd' => '4',
        ['e', '!=', 5],
    ])
    ->where(function ($query) {
        $query->whereNull('f');
    });

$case = CaseExpr::make()
    ->when($caseBuilder)
    ->then('Complex Condition Met')
    ->else('Condition Not Met')
    ->as('result');
```

### Using the selectCase Macro

[](#using-the-selectcase-macro)

The package provides a convenient `selectCase` macro for cleaner syntax:

```
use App\Models\User;

$users = User::query()
    ->select(['id', 'name'])
    ->selectCase('status_label', function ($case) {
        $case
            ->when('status', '=', 'active')
            ->then('Active')
            ->when('status', '=', 'inactive')
            ->then('Inactive')
            ->else('Unknown');
    })
    ->get();
```

### Multiple CASE Expressions

[](#multiple-case-expressions)

You can use multiple CASE expressions in a single query:

```
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$users = User::query()
    ->select([
        'id',
        'name',
        CaseExpr::make()
            ->when('email_verified_at', '!=', null)
            ->then('Verified')
            ->else('Unverified')
            ->as('email_status'),
        CaseExpr::make()
            ->when('phone_verified_at', '!=', null)
            ->then('Verified')
            ->else('Unverified')
            ->as('phone_status'),
        CaseExpr::make()
            ->when('created_at', '>', now()->subDays(30))
            ->then('New User')
            ->else('Existing User')
            ->as('user_type')
    ])
    ->get();
```

### Real-World Examples

[](#real-world-examples)

#### Example 1: User Status with Multiple Conditions

[](#example-1-user-status-with-multiple-conditions)

```
use App\Models\User;
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$users = User::query()
    ->select([
        'id',
        'name',
        CaseExpr::make()
            ->when('email_verified_at', '!=', null)
            ->then(
                CaseExpr::make()
                    ->when('phone_verified_at', '!=', null)
                    ->then('Fully Verified')
                    ->else('Email Verified Only')
            )
            ->when('phone_verified_at', '!=', null)
            ->then('Phone Verified Only')
            ->else('Unverified')
            ->as('verification_status')
    ])
    ->get();
```

#### Example 2: Order Priority Based on Amount and Date

[](#example-2-order-priority-based-on-amount-and-date)

```
use Illuminate\Support\Facades\DB;
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$orders = DB::table('orders')
    ->select([
        'id',
        'customer_id',
        'total',
        CaseExpr::make()
            ->when('total', '>', 1000)
            ->then('High Priority')
            ->when('total', '>', 500)
            ->then(
                CaseExpr::make()
                    ->when('created_at', '>', now()->subDays(7))
                    ->then('Medium Priority - Recent')
                    ->else('Medium Priority')
            )
            ->else('Low Priority')
            ->as('priority')
    ])
    ->get();
```

#### Example 3: Dynamic Pricing Tiers

[](#example-3-dynamic-pricing-tiers)

```
use App\Models\Product;
use ByteGourmet\LaravelConditionalExpressions\CaseExpr;

$products = Product::query()
    ->select([
        'id',
        'name',
        'price',
        CaseExpr::make()
            ->when('price', '>=', 1000)
            ->then('Premium')
            ->when('price', '>=', 500)
            ->then('Standard')
            ->when('price', '>=', 100)
            ->then('Basic')
            ->else('Economy')
            ->as('tier')
    ])
    ->get();
```

API Reference
-------------

[](#api-reference)

### CaseExpr

[](#caseexpr)

The main facade class for creating CASE expressions.

#### Methods

[](#methods)

##### `CaseExpr::make(?string $column = null)`

[](#caseexprmakestring-column--null)

Creates a new searched CASE expression (or simple CASE if column is provided).

```
$case = CaseExpr::make(); // Searched CASE
$case = CaseExpr::make('status'); // Simple CASE
```

##### `CaseExpr::simple(string $column)`

[](#caseexprsimplestring-column)

Creates a simple CASE expression for the given column.

```
$case = CaseExpr::simple('status');
```

##### `CaseExpr::builder()`

[](#caseexprbuilder)

Creates a new `CaseBuilder` instance for complex conditions.

```
$builder = CaseExpr::builder();
```

### CaseExpression

[](#caseexpression)

The expression class that builds the CASE statement.

#### Methods

[](#methods-1)

##### `when(string|CaseBuilder|Expression $column, ?string $operator = null, mixed $value = null)`

[](#whenstringcasebuilderexpression-column-string-operator--null-mixed-value--null)

Adds a WHEN clause to the CASE expression.

```
$case->when('status', '=', 'active');
$case->when($caseBuilder); // Using CaseBuilder
```

##### `then(mixed $result)`

[](#thenmixed-result)

Sets the THEN value for the last WHEN clause. Accepts scalar values or nested `CaseExpression`.

```
$case->then('Active');
$case->then(CaseExpr::make()->when(...)->then(...)); // Nested
```

##### `else(mixed $result)`

[](#elsemixed-result)

Sets the ELSE value. Accepts scalar values or nested `CaseExpression`.

```
$case->else('Unknown');
```

##### `as(string $alias)`

[](#asstring-alias)

Sets an alias for the CASE expression.

```
$case->as('status_label');
```

##### `toSql()`

[](#tosql)

Returns the generated SQL string.

```
$sql = $case->toSql();
```

##### `getBindings()`

[](#getbindings)

Returns the parameter bindings array.

```
$bindings = $case->getBindings();
```

### CaseBuilder

[](#casebuilder)

Extends Laravel's Query Builder for building complex WHERE conditions.

#### Methods

[](#methods-2)

##### `CaseBuilder::query()`

[](#casebuilderquery)

Creates a new CaseBuilder instance.

```
$builder = CaseExpr::builder();
```

##### `getConditions()`

[](#getconditions)

Returns the compiled WHERE conditions as a string.

```
$conditions = $builder->getConditions();
```

All standard Laravel Query Builder methods are available (`where`, `orWhere`, `whereNull`, etc.).

Debugging
---------

[](#debugging)

You can debug your CASE expressions using the provided helper methods:

```
$case = CaseExpr::make()
    ->when('status', '=', 'active')
    ->then('Active')
    ->else('Inactive');

// Dump the SQL
$case->dump();

// Dump and die
$case->dd();
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

Credits
-------

[](#credits)

- **Author**: Riju Ghosh

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance79

Regular maintenance activity

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

110d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/75ec18bfb8a5ac6120b0d92df33bf1ceefc9657ce7ac3c60f7decba489f4756c?d=identicon)[ghoshriju33](/maintainers/ghoshriju33)

---

Top Contributors

[![sdsrg22](https://avatars.githubusercontent.com/u/142865036?v=4)](https://github.com/sdsrg22 "sdsrg22 (3 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

### Embed Badge

![Health badge](/badges/bytegourmet-laravel-conditional-expressions/health.svg)

```
[![Health](https://phpackages.com/badges/bytegourmet-laravel-conditional-expressions/health.svg)](https://phpackages.com/packages/bytegourmet-laravel-conditional-expressions)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[wearepixel/laravel-cart

A cart implementation for Laravel

1355.6k](/packages/wearepixel-laravel-cart)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
