Table of Contents
1- Initialization project
2- Routing
3- Controller
4- UsersResource class
5- UsersResourceCollection class
Home PHP Framework Laravel How to dynamically hide API fields in Laravel

How to dynamically hide API fields in Laravel

Mar 24, 2021 pm 05:38 PM
laravel php

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
        ];
    }
}
Copy after login

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
Copy after login

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

DB_CONNECTION=sqlite
Copy after login

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
Copy after login

2- Routing

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

Route::apiResource('/users', 'UsersController');
Copy after login

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']);
    }
}
Copy after login

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();
    }
}
Copy after login

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"
 }
}
Copy after login

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();
    }
}
Copy after login
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();
    }
}
Copy after login
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
 }
}
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

See all articles