Skip to content

Instantly share code, notes, and snippets.

@ManojKiranA
Last active July 2, 2020 14:13
Show Gist options
  • Save ManojKiranA/116b916a1d005268a7f88ff294eb9c2b to your computer and use it in GitHub Desktop.
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
<?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