3

Laravel has the option to add an $appends array to each model making additional values automatically available as if they are database attributes by adding accessors for each.

This is normally pretty handy, except in this case I need to ONLY get the fields I put into select() because DataTables is expecting only what I send to it.

Example:

Item::select(['image', 'name', 'color']);

Will return appended fields after color in the attributes.

How do I force the exclusion of the appends values when returning results?

Or alternatively, how do I get DataTables to ignore certain attributes?

Not sure which is the least time costly route.

Currently using yajra/laravel-datatables package to send data to the jQuery DataTables AJAX request.

miken32
  • 42,008
  • 16
  • 111
  • 154
eComEvo
  • 11,669
  • 26
  • 89
  • 145

2 Answers2

3

You can call each function in the collection object and then use setHidden method to exclude the unwanted fields like this

$item= Item::select(['image', 'name', 'color'])->get()->each(function($row){
                    $row->setHidden(['appendedField1', 'appendedField2']);
                });

And for the yajra/laravel-datatables you can use something like

$item= Item::select(['image', 'name', 'color']);
return Datatables::of($item)->remove_column('appendedField1');
Milan Maharjan
  • 4,156
  • 1
  • 21
  • 28
  • Unfortunately I can't use `get()` on the results before passing to `yajra/laravel-datatables` package which passes it to the jQuery DataTables package over AJAX. Forgot to mention that package. Otherwise this would be a perfect solution! – eComEvo Oct 29 '15 at 22:36
  • I think you can use remove_column('columnName') method in yajra/laravel-datatables package. – Milan Maharjan Oct 30 '15 at 09:08
  • To solve this I made `$appends` public on my `Item` model, created var `$DT = Datatables::of($items);` and then used `call_user_func_array([$DT, 'removeColumn'], $items->first()->appends);` before returning `make()`. Has to be called this way with `yajra/laravel-datatables-oracle` v3 if passing an array. – eComEvo Oct 30 '15 at 14:43
  • Correction, can't do it that way or it messes up pagination. Had to create static method for it which I've posted in a solution. +1 your answer for helping me figure out full solution. – eComEvo Oct 30 '15 at 16:26
1

To solve this I added this method to my Item model:

public static function getAppends()
{
    $vars = get_class_vars(__CLASS__);

    return $vars['appends'];
}

Then used the following code in the controller:

$items = Item::select(['image', 'name', 'color']);

$DT = Datatables::of($items);

call_user_func_array([$DT, 'removeColumn'], Item::getAppends()); // Has to be called this way with yajra/laravel-datatables-oracle v3.* if passing an array.

return $DT->make(true);
eComEvo
  • 11,669
  • 26
  • 89
  • 145