Last active
July 2, 2020 14:13
-
-
Save ManojKiranA/116b916a1d005268a7f88ff294eb9c2b to your computer and use it in GitHub Desktop.
Useful Laravel Function, Classes, Traits, Mixins, Macros and Much More laravel Related stuff
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 | |
namespace App\Models; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Facades\Cache; | |
use Illuminate\Support\Str; | |
use RecursiveArrayIterator; | |
use RecursiveIteratorIterator; | |
class BaseModel extends Model | |
{ | |
/** | |
* Shows All the columns of the Corresponding Table of Model. | |
* | |
* If You need to get all the Columns of the Model Table. | |
* Useful while including the columns in search | |
* @return array | |
**/ | |
public function getTableColumns():array | |
{ | |
$cacheKey = Str::of(get_class($this)) | |
->append(':') | |
->append('COLUMNS_OF_TABLE') | |
->__toString(); | |
return Cache::rememberForever($cacheKey, function () { | |
return $this->getConnection() | |
->getSchemaBuilder() | |
->getColumnListing($this->getTable()); | |
}); | |
} | |
/** | |
* Scope a query to only exclude specific Columns. | |
* | |
* @param \Illuminate\Database\Eloquent\Builder $query | |
* @return \Illuminate\Database\Eloquent\Builder | |
*/ | |
public function scopeExclude($query, ...$columns) | |
{ | |
if ($columns !== []) { | |
if (count($columns) !== count($columns, COUNT_RECURSIVE)) { | |
$columns = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($columns))); | |
} | |
return $query->select(array_diff($this->getTableColumns(), $columns)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment