Created
December 1, 2023 05:14
-
-
Save AnandPilania/625bfa3c4e38d6556b108f29001504e4 to your computer and use it in GitHub Desktop.
Laravel: Model common utility trait
This file contains 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 | |
namespace App\Concerns; | |
use DB; | |
use Illuminate\Database\Eloquent\Builder; | |
use Schema; | |
/** | |
* Trait ModelConcern | |
* @method void|static search($query) | |
*/ | |
trait ModelConcern | |
{ | |
public function persist($data, $save = true) | |
{ | |
foreach ($data as $key => $value) { | |
$this->$key = $value; | |
} | |
if ($save) { | |
$this->save(); | |
} | |
return $this; | |
} | |
public function scopeSearch(Builder $query, $s): mixed | |
{ | |
if (blank($s)) { | |
return $query; | |
} | |
$column = $this->search_fields | |
? $this->search_fields | |
: Schema::getColumnListing($this->getTable()); | |
foreach ($column as $key => $c) { | |
if (is_array($c)) { | |
$relation = $c; | |
$query->orWhereHas($c[0], function ($q) use ($relation, $s) { | |
foreach ($relation[1] as $key => $column) { | |
if ($column === 'full_name') { | |
$column = DB::raw('CONCAT(first_name," ",last_name)'); | |
$q->where($column, 'LIKE', '%'.$s.'%'); | |
} else { | |
$method = $key ? 'orWhere' : 'where'; | |
$q->{$method}($column, 'LIKE', "%{$s}%"); | |
} | |
} | |
}); | |
} else { | |
$method = $key ? 'orWhere' : 'where'; | |
if ($c === 'full_name') { | |
$c = DB::raw('CONCAT(first_name," ",last_name)'); | |
} | |
$query->{$method}($c, 'LIKE', "%{$s}%"); | |
} | |
} | |
return $query; | |
} | |
public function scopeActive($q, $s) | |
{ | |
if (! is_null($s) && $s == '1' || $s == '0') { | |
$q->where('active', $s); | |
} | |
return $q; | |
} | |
public function scopeSort($q, $orderBy, $orderDirection) | |
{ | |
return $q->orderBy($orderBy, $orderDirection); | |
} | |
public function scopeFindByArgs($q, $args) | |
{ | |
if (is_array($args) && count($args)) { | |
foreach ($args as $column => $value) { | |
$q->where($column, $value); | |
} | |
} | |
} | |
public function scopeFilterByParentID($query, $parentId) | |
{ | |
$query->where('parent_id', $parentId); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment