1

I need to send specific fields from the API resource

here is my User resource code

namespace App\Http\Resources;

use App\Models\MediaFile;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;

class User extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $attributes = $this->getAttributes();
        unset($attributes['password']);

        return [
            'type' => 'users',
            'attributes' => $attributes,
        ];
    }
}

Below are my attributes

"attributes": {
        "id": "1",
        "email": "email",
        "full_name": "Name",
        "permission": "admin",
        "security_key": "alpha",
        "token": "encrypted token",
        "two_factor_enabled": "true",
        "created_at": "2020-05-15 08:56:50",
        "updated_at": "2020-05-15 08:56:57",
      }

I would like hide specific fields in specific routes. How can I implement this?

2
  • laravel.com/docs/5.8/… You can use $hidden property. Commented May 15, 2020 at 16:17
  • $hidden will hide, for all the routes. But i need to hide specific fields in specific methods Commented May 15, 2020 at 16:24

2 Answers 2

2

use makeHidden

$user = \App\Models\User::firstOrFail();

$user->makeHidden(['email', 'phone']);

return $user;
Sign up to request clarification or add additional context in comments.

Comments

2

You can use two approaches:

$attributes = [
    "id"=> "1",
    "email" => "pera",
    "full_name" => "Name",
    "permission" => "admin",
    "security_key" => "alpha",
    "token" => "encrypted token",
    "two_factor_enabled" => "true",
    "created_at" => "2020-05-15 08:56:50",
    "updated_at" => "2020-05-15 08:56:57",
];
  1. PHP approach: unset($attributes['id'], $attributes['security_key']);
  2. Laravel approach: Arr::except($attributes, ['id','security_key']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.