search
HomePHP FrameworkLaravelHow to dynamically hide API fields in Laravel

The following tutorial column from laravel will introduce to you how to dynamically hide API fields in Laravel. I hope it will be helpful to friends in need!

How to dynamically hide API fields in Laravel

Dynamic hiding of API fields in Laravel

I recently saw a question in the Laravel Brasil community, and the result was It looks more interesting. Imagine you have a UsersResource implemented with the following:

<?php namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class UsersResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            &#39;id&#39; => $this->id,
            'name' => $this->name,
            'email' => $this->email
        ];
    }
}

For some reason, you might want to reuse that resource class on another endpoint, but hide email Field. This article tells you how to achieve this.
If you don’t know what API Resources are, please check out my previous article about this.

  • First Impression on API Resources
  • API Resources with Nested Relationship

1- Initialization project

Interesting stuff Start with Section 3.

composer create-project --prefer-dist laravel/laravel api-fields
cd api-fields
touch database/database.sqlite

Edit the .env file, remove the database settings and continue setting up the project using SQLite

DB_CONNECTION=sqlite

php artisan migrate
php artisan make:resource UsersResource
php artisan make:resource --collection UsersResourceCollection 
php artisan make:controller UsersController
php artisan tinker
factory(App\User::class)->times(20)->create();
quit

2- Routing

Make sure to create a route in the api.php file.

Route::apiResource('/users', 'UsersController');

3- Controller

The controller represents the desired goal. In this example, let's assume that in the users list we only want the names of all users, and in the users display we only want to hide the email addresses.

<?php namespace App\Http\Controllers;
use App\Http\Resources\UsersResource;
use App\User;
class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param User $user
     * @return \Illuminate\Http\Response
     */
    public function index(User $user)
    {
        return UsersResource::collection($user->paginate())->hide(['id', 'email']);
    }
    /**
     * Display a user.
     *
     * @param User $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        return UsersResource::make($user)->hide(['id']);
    }
}

To achieve this, we need UsersResourceCollection and UsersResource to both know how to handle hide calls.

4- UsersResource class

Let’s start with the show method. UsersResource::make will return UsersResource Object. Therefore, we should demystify hide which stores the keys we wish to remove from the response.

<?php namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class UsersResource 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([
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email
        ]);
    }
    /**
     * 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)->forget($this->withoutFields)->toArray();
    }
}

Done! Now we can access http: //api.dev/api/users/1, you will find that there is no id field in the response.

{
 "data": {
  "name": "Mr. Frederik Morar",
  "email": "darryl.wilkinson@example.org"
 }
}

5- UsersResourceCollection class

Execute the index method in the project collection, we need to make the following modifications:

  • (1) Ensure UsersResource::collection Returns UsersResourceCollection instance
  • (2) Public hide method# on UsersResourceCollection
  • ##(3) Pass the hidden fields to
  • UsersResource
Regarding (1), we only need to rewrite the

collection in UsersResource Methods

<?php namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class UsersResource extends Resource
{
    public static function collection($resource)
    {
        return tap(new UsersResourceCollection($resource), function ($collection) {
            $collection->collects = __CLASS__;
        });
    }
    
    /**
     * @var array
     */
    protected $withoutFields = [];
    /**
     * Transform the resource into an array.
     * 将资源转换为一个数组
     * 
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return $this->filterFields([
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email
        ]);
    }
    /**
     * 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)->forget($this->withoutFields)->toArray();
    }
}
Regarding (2) and (3) we need to modify the

UsersResourceCollection file. Let’s expose the hide method and use hidden fields to handle the collection. .

<?php namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UsersResourceCollection extends ResourceCollection
{
    /**
     * @var array
     */
    protected $withoutFields = [];
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return $this->processCollection($request);
    }
    public function hide(array $fields)
    {
        $this->withoutFields = $fields;
        return $this;
    }
    /**
     * Send fields to hide to UsersResource while processing the collection.
     *  将隐藏字段通过 UsersResource 处理集合
     * 
     * @param $request
     * @return array
     */
    protected function processCollection($request)
    {
        return $this->collection->map(function (UsersResource $resource) use ($request) {
            return $resource->hide($this->withoutFields)->toArray($request);
        })->all();
    }
}
It’s that simple! Now we visit

http://api.dev/api/users and see that id and are not included in the returned results. The email field is as specified in the method in UsersController.

{
 "data": [{
  "name": "Mr. Frederik Morar"
 }, {
  "name": "Angel Daniel"
 }, {
  "name": "Brianne Mueller"
 }],
 "links": {
  "first": "http://lab.php71/api-fields-2/public/api/users?page=1",
  "last": "http://lab.php71/api-fields-2/public/api/users?page=7",
  "prev": null,
  "next": "http://lab.php71/api-fields-2/public/api/users?page=2"
 },
 "meta": {
  "current_page": 1,
  "from": 1,
  "last_page": 7,
  "path": "http://api-fields.lab.php71/api/users",
  "per_page": 3,
  "to": 3,
  "total": 20
 }
}
6- Summary

The goal of this article is to let the

Resource class pass the hidden Some fields are allowed to be exposed in other interfaces to make them more flexible. For example, when we request the /users interface, the response data does not contain the avatar field, but when we request /users/99, the response data contains avatarField.

I do not recommend excessively repeated requests for API resources, because it is likely to make simple things more complicated, so hiding certain specific fields when requesting is a simpler and more reasonable solution. plan.

Recommended:

The latest five Laravel video tutorials

The above is the detailed content of How to dynamically hide API fields in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Most Recent Laravel Version: Discover What's NewThe Most Recent Laravel Version: Discover What's NewMay 12, 2025 am 12:15 AM

Laravel10introducesseveralkeyfeaturesthatenhancewebdevelopment.1)Lazycollectionsallowefficientprocessingoflargedatasetswithoutloadingallrecordsintomemory.2)The'make:model-and-migration'artisancommandsimplifiescreatingmodelsandmigrations.3)Integration

Laravel Migrations Explained: Create, Modify, and Manage Your DatabaseLaravel Migrations Explained: Create, Modify, and Manage Your DatabaseMay 12, 2025 am 12:11 AM

LaravelMigrationsshouldbeusedbecausetheystreamlinedevelopment,ensureconsistencyacrossenvironments,andsimplifycollaborationanddeployment.1)Theyallowprogrammaticmanagementofdatabaseschemachanges,reducingerrors.2)Migrationscanbeversioncontrolled,ensurin

Laravel Migration: is it worth using it?Laravel Migration: is it worth using it?May 12, 2025 am 12:10 AM

Yes,LaravelMigrationisworthusing.Itsimplifiesdatabaseschemamanagement,enhancescollaboration,andprovidesversioncontrol.Useitforstructured,efficientdevelopment.

Laravel: Soft Deletes performance issuesLaravel: Soft Deletes performance issuesMay 12, 2025 am 12:04 AM

SoftDeletesinLaravelimpactperformancebycomplicatingqueriesandincreasingstorageneeds.Tomitigatetheseissues:1)Indexthedeleted_atcolumntospeedupqueries,2)Useeagerloadingtoreducequerycount,and3)Regularlycleanupsoft-deletedrecordstomaintaindatabaseefficie

What Are Laravel Migrations Good For? Use Cases and BenefitsWhat Are Laravel Migrations Good For? Use Cases and BenefitsMay 11, 2025 am 12:14 AM

Laravelmigrationsarebeneficialforversioncontrol,collaboration,andpromotinggooddevelopmentpractices.1)Theyallowtrackingandrollingbackdatabasechanges.2)Migrationsensureteammembers'schemasstaysynchronized.3)Theyencouragethoughtfuldatabasedesignandeasyre

How to Use Soft Deletes in Laravel: Protecting Your DataHow to Use Soft Deletes in Laravel: Protecting Your DataMay 11, 2025 am 12:14 AM

Laravel's soft deletion feature protects data by marking records rather than actual deletion. 1) Add SoftDeletestrait and deleted_at fields to the model. 2) Use the delete() method to mark the delete and restore it using the restore() method. 3) Use withTrashed() or onlyTrashed() to include soft delete records when querying. 4) Regularly clean soft delete records that have exceeded a certain period of time to optimize performance.

What are Laravel Migrations and How Do You Use Them?What are Laravel Migrations and How Do You Use Them?May 11, 2025 am 12:13 AM

LaravelMigrationsareversioncontrolfordatabaseschemas,allowingreproducibleandreversiblechanges.Tousethem:1)Createamigrationwith'phpartisanmake:migration',2)Defineschemachangesinthe'up()'methodandreversalin'down()',3)Applychangeswith'phpartisanmigrate'

Laravel migration: Rollback doesn't work, what's happening?Laravel migration: Rollback doesn't work, what's happening?May 11, 2025 am 12:10 AM

Laravelmigrationsmayfailtorollbackduetodataintegrityissues,foreignkeyconstraints,orirreversibleactions.1)Dataintegrityissuescanoccurifamigrationaddsdatathatcan'tbeundone,likeacolumnwithadefaultvalue.2)Foreignkeyconstraintscanpreventrollbacksifrelatio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)