Search code examples
laravelapilaravel-apilaravel-resource

How to send specific fields in Laravel Resource


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?


Solution

  • use makeHidden

    $user = \App\Models\User::firstOrFail();
    
    $user->makeHidden(['email', 'phone']);
    
    return $user;