GodziLaravel's avatar

how to keep pagination after transform() ?

Hello ,

this is my code :

$exceptions = [1,4,7,88,5,8]
    $data = \App\User::select(['id','name','city','post_code', 'email'])->paginate(10)
        ->transform(function($item) use($exceptions ){
        if (!in_array($item->id ,$exceptions )){
            $item->email = null;
        }
        return $item;
    });

return $data;

The problem is return $data; returns the data I need but without pagination !

Is it possible to get also the pagination ?

Thanks

0 likes
6 replies
Sirik's avatar

Loop your pagination data and use

$data = \App\User::select(['id','name','city','post_code', 'email'])->paginate(10);
return $data;
// User.php add

public function getEmailAttribute($value)
    {
        return in_array($this->id, [1,4,7,88,5,8]) ? $value : null;
    }

in your blade view use

	$user->email
GodziLaravel's avatar

@sirik that's not possible through the model what I'm looking is to do that locally in the controller the real request is more complicated than the one I shown above .

Sirik's avatar

Did my latest reply helped you out?

webrobert's avatar

@godzilaravel , here's an example,

I pluck out the data portion of the paginate to send elsewhere

			$paginate = Place::simplePaginate(20);
			$this->updateMapData(collect($paginate)['data']);
			return $paginate;

Not sure if this is the best practice but as @silencebringer mentioned returning the json, instead, I've also done something similar to this sample to replace the data with the transformed version.

Please or to participate in this conversation.