DolDurma
DolDurma

Reputation: 17301

Laravel hide or remove some database column data from result

in Laravel API i have some method which they are return some fields which i don't want to have in result, for example:

id  -  email  -  user_id

and they are optional and i can't set this fields into self models, now i'm using this class as ManageResource to hode/remove fields/columns from result like this code:

$user = User::whereApiToken($request->api_token)->first();
$result = ManageResource::make($user)->hide(['id','email']);

after using this code that implemented by below class i get only id and email on array keys, but i want to hide them

ManageResource class:

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;

class ManageResource extends Resource
{
    /**
     * @var array
     */
    protected $withoutFields = [];

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return $this->filterFields($this->withoutFields);
    }

    /**
     * Set the keys that are supposed to be filtered out.
     *
     * @param array $fields
     * @return $this
     */
    public function hide(array $fields)
    {
        $this->withoutFields = $fields;
        return $this;
    }

    /**
     * Remove the filtered keys.
     *
     * @param $array
     * @return array
     */
    protected function filterFields($array)
    {
        return collect($array)->toArray();
    }
}

Upvotes: 8

Views: 19976

Answers (6)

The EasyLearn Academy
The EasyLearn Academy

Reputation: 927

$_SESSION['data'] = array();
   $rows= Product::with('category')->get()
        ->map(function ($rows) {
            array_push($_SESSION['data'],array(
                'id' => $rows->id,
                'title' => $rows->title,
                'price' => $rows->price,
                'photo' => $rows->price,
                'categorytitle' => $rows->category->title,
                'created_at' => $rows->getCreationDate(),
                'updated_at' => $rows->getUpdationDate(),

            ));
        });
   $data = $_SESSION['data'];
   unset($_SESSION['data']);
   return view("products")->with("result",$data);

Upvotes: 0

Amitesh Bharti
Amitesh Bharti

Reputation: 15703

As you would like to make some typically visible attributes hidden on a given model instance, you may use the makeHidden method.

return $user->makeHidden('attribute')->toArray();

Here, $user represents user model

Example Case : use makeHidden with code to hide column in pagination result

$result = Job::where('user_id','=',Auth::id())->paginate(5);
$data =$result;
$result= $result->makeHidden(['hasMessage']);
$data->data = $result;
return $data;

In Your case :

$result = ManageResource::make($user)->makeHidden(['id','email'])->toArray();
$data->data = $result;
return $data;

or

$result = User::whereApiToken($request->api_token)->first()->setHidden(['id', 'email']);
$data->data = $result;
return $data;

Note :

As far as I'm aware, makeHidden doesn't affect relations. It would have been good if it allowed you to specify attributes in relations as -makeHidden(['relation.field']). Alternatively you can use following code

App\Models\Product::with(['images' => function ($query) {             
 $query->select(['id','product_id','image_url',   
'row_id'])->orderBy('created_at', 'desc');                            
}])->get()->makeHidden(['id']);

In your case

$tickets = UserTickets::with(['user', 'reply' => function ($query) use ($user) {
    $query->with('user')->select(['id','Attrib1','Attrib2'])->whereUserId($user->id);
}])->whereTicketNumber($request->ticket_number)->get();

Upvotes: 16

Yamen Ashraf
Yamen Ashraf

Reputation: 2950

User::select('name')->get();
User::select('name', 'email')->get();
User::all()->pluck('name'); // array

Upvotes: 1

Niklas
Niklas

Reputation: 1777

Wouldn't the easiest way be to use the setHidden() method on the model itself?

$user = User::whereApiToken($request->api_token)->first()->setHidden(['id', 'email']);

echo $user;

Given the table/field structure id - email - user_id this should result in something like:

{"user_id": 1}

Upvotes: 1

Vinoth Sd
Vinoth Sd

Reputation: 112

You can use map filter to get the desired fields.

$events= Events::where(['id' => 1])->get()
            ->map(function ($event) {
                return [
                    'id' => $event->id,
                    'title' => $event->title,
                    'target' => $event->specific,
                    'date' => $event->start . '-' . $event->end,
                    'created' => $event->created_at
                ];
            });

Upvotes: 1

FULL STACK DEV
FULL STACK DEV

Reputation: 15941

you can use get()

$result = new (ManageResource($user))->get(['name']);

it will return only the values that you want.

Upvotes: 0

Related Questions