Laravel connects you with PHP

Sometimes when querying some Models we want to exclude colmuns from the results, the same as using except in the collections. In that operation we will be using two new things, the first one is PHP’s Traits and the second one is the local scopes.

TRAITS

The way I think of trait is a class that holds some functions/attributes that will be used very often, Actually its a solution to not use multiple inheretance and a solution to not to use Interfaces since you’ll have to implement the same code.

SCOPES

Scopes are nothing but a way to add a constraints to queries, Actually there are two kind of scopes global/local. I’d recomand you to read Laravel’s documentation, can’t be explained better than the way Taylor Otwell did.

The Implementation

Now we will make the trait that will hold the logic of excluding the specific columns. There is no special place to put the file, for me I always like to put it in a folder in the App.

namespace App\Traits;

trait Excludable {

}

Our trait will hold two method, the first one will just return an array of column existing in the table corresponding to the model.

/**
* Get the array of columns
* @return mixed
*/
private function getTableColumns() {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}

The second method will select the difference of the array of columns that we have got using the helper method and the colmuns that will be excluded.

/**
* Exclude an array of elements from the result.
* @param $query
* @param $columns
* @return mixed
*/
public function scopeExclude($query, $columns)
{
return $query->select(array_diff($this->getTableColumns(), (array) $columns));
}

I suppose you have read the documentation and you know the syntax and the parameters of the method.

The last part will be to use that trait in the Models you want to exclude colmuns from when you perform select(of cours when you want that).

namespace App;

use App\Traits\Excludable;
use Illuminate\Database\Eloquent\Model;

class Medicine extends Model
{
use Excludable;
protected $fillable = ['name', 'description'];
}

And this is how to use it

$medicines = \App\Medicine::exclude('description')->get();

Hope it was helpfull, don’t forget to share it with your network.

Happy coding!!