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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles