jeudi 30 novembre 2017

Laravel 5.5 Inconsistent JSON when using filter on a collection

I am building a simple search for a project I am working on. It works fairly well for the most part. I am running into an issue when using ->filter(function($item) { .. }).

Here is the code:

$users = App\User::select(['id', 'username', 'preferred_first_name', 'preferred_last_name'])
        ->where('username', 'like', $like)
        ->orWhere('preferred_first_name', 'like', $like)
        ->orWhere('preferred_last_name', 'like', $like)
        ->orWhere('id', $query)
        ->get();
$users = $users->filter(function($item) {
    return !$item->is_terminated();
});
return UserResource::collection($users);

And here is the toArray function in UserResource:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'username' => $this->username,
        'full_name' => $this->full_name,
    ];
}

The issue I am having is some of the JSON is returned in two different formats:

Format A: { data: [ {..}, {..}, .. ] }
Format B: { data: {"0": {..}, "1":{..},..} }

I would like all the JSON to be returned in Format A all the time. I've narrowed it down the filter() function. But it is inconsistent. On the search term san it returns in Format B but on the term pha it returns in Format A. If removed everything works perfectly and is returned in the proper format (Format A).

If there's any code missing that could help let me know as I am unsure what needs to be included.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2jzipUk
via IFTTT

Aucun commentaire:

Enregistrer un commentaire