Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Created February 8, 2024 09:38
Show Gist options
  • Save AnandPilania/6086ea801703a23b650d7c91633795bc to your computer and use it in GitHub Desktop.
Save AnandPilania/6086ea801703a23b650d7c91633795bc to your computer and use it in GitHub Desktop.
Dynamic Conditional Checks in Laravel Eloquent Base Model

This Laravel Eloquent base model enhancement provides a dynamic method handling mechanism for conditional checks based on column values.

The __call magic method is utilized to interpret method calls ending with Is or IsNot. The associated column is extracted, and the method dynamically checks if the column's value matches or does not match specified values.

This allow to handle multiple parameters, enhancing its flexibility. This concise and expressive approach simplifies conditional checks, making the code more readable and adaptable in various scenarios.

// Assuming there's a 'status' column in the model

// Check if status is one of [1, 2, 3]
$result = $model->statusIs(1, 2, 3);

// Check if status is not one of [4, 5, 6]
$result = $model->statusIsNot(4, 5, 6);

// Check if another_column is one of [7, 8, 9]
$result = $model->anotherColumnIs(7, 8, 9);

// Check if enum_column is/one of Status::DRAFT || [Status::DRAFT, Status::INACTIVE]
$result = $model->enumColumnIs(Status::DRAFT);
$result = $model->enumColumnIs(Status::DRAFT, Status::INACTIVE);
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Base;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
abstract class Model extends Base
{
public function __call($method, $parameters)
{
$column = null;
$strMethod = Str::of($method);
if ($endsWithIs = $strMethod->endsWith('Is')) {
$column = $strMethod->snake()->beforeLast('_is');
} elseif ($strMethod->endsWith('IsNot')) {
$column = $strMethod->snake()->beforeLast('_is_not');
}
if (isset($column, $this->{$column})) {
$array = Arr::wrap($parameters);
return $endsWithIs
? in_array($this->{$column}, $array, true)
: ! in_array($this->{$column}, $array, true);
}
return parent::__call($method, $parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment