Skip to content

Instantly share code, notes, and snippets.

@extralam
Last active December 25, 2018 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save extralam/37412e2729b5109c0f1b9a6b86f27cc7 to your computer and use it in GitHub Desktop.
Save extralam/37412e2729b5109c0f1b9a6b86f27cc7 to your computer and use it in GitHub Desktop.
Laravel Eloquent Model Enhancement.
<?php
/**
* User: extralam
* Date: 24/12/2018
* Time: 5:47 PM
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class BaseModel extends Model
{
public static function __callStatic($method, $params)
{
if (starts_with($method, "findOne")) {
$fieldname = lcfirst(substr($method, strlen("findOne")));
$clazz = get_called_class();
return $clazz::where("$fieldname", $params[0])->first();
}
if (starts_with($method, "findBy")) {
$fieldname = substr($method, strlen("findBy"));
$fieldnamesAnd = explode("And", $fieldname);
$fieldnamesOr = explode("Or", $fieldname);
if (count($fieldnamesAnd) > 1 && count($fieldnamesOr) > 1) {
} else {
$clazz = get_called_class();
$result = $clazz::where(DB::raw('1'), '1');
if (count($fieldnamesAnd) > 1) {
foreach ($fieldnamesAnd as $key => $field) {
$result = $result->where(lcfirst($field), $params[$key]);
}
}
if (count($fieldnamesOr) > 1) {
foreach ($fieldnamesAnd as $key => $field) {
$result = $result->orWhere(lcfirst($field), $params[$key]);
}
}
return $result->get();
}
}
return parent::__callStatic($method, $params);
}
}
@extralam
Copy link
Author

Now You can write something like this

class Member extends BaseModel{
}
// find one member id = 1
Member::findOneId(1);
// list all member is Male
Member::findByGender("M");
// list all member is Male and active = 1
Member::findByGenderAndActive("M", 1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment