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);