Last active
December 25, 2018 11:07
-
-
Save extralam/37412e2729b5109c0f1b9a6b86f27cc7 to your computer and use it in GitHub Desktop.
Laravel Eloquent Model Enhancement.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now You can write something like this