naotake51/laravel-recursive-only

注册 recursiveOnly(),仅扩展 Model、Collection 和 Arr。

v1.0.0 2022-04-21 17:07 UTC

This package is auto-updated.

Last update: 2024-09-15 20:25:44 UTC


README

使 Laravel 的 only 更有用。

  • 递归
  • *(任意键)
  • 回调

要求

  • PHP: ^7.1 || ^8.0
  • Laravel: ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0

安装

composer require naotake51/laravel-recursive-only

动机

我发现 Laravel 的深度嵌套 Resource 定义起来很痛苦。

我希望更简单地编写 Resource

使用

你的模型添加 trait RecursiveOnly

use Naotake51\RecursiveOnly\Contracts\HasRecursiveOnly;
use Naotake51\RecursiveOnly\Traits\RecursiveOnly;

class Post extends Model implements HasRecursiveOnly
{
    use RecursiveOnly;

    // ...
}

调用 recursiveOnly

  • * 表示任意键。
  • 值可以在回调中更改。
$post = Post::with(['author', 'comments'])->find(1);

$data = $post->recursiveOnly([
    'author' => [
        'name'
    ],
    'comments' => [
        '*' => [
            'title' => fn ($value /**, ...parents */) => "# $value", // use callback
            'body',
        ]
    ]
]);

// $data => [
//     'author' => [
//         'name' => '...'
//     ],
//     'comments' => Illuminate\Support\Collection([
//         [
//             'title' => '# ...',
//             'body' => '...',
//         ],
//         ...
//     ])
// ]
$posts = Post::with(['author', 'comments'])->get();

$data = $posts->recursiveOnly([
    '*' => [
        'author' => [
            'name'
        ],
        'comments' => [
            '*' => [
                'body'
            ]
        ]
    ]
]);

// $data => Illuminate\Support\Collection([
//     [
//         'author' => [
//             'name' => '...'
//         ],
//         'comments' => Illuminate\Support\Collection([
//             [
//                 'body' => '...'
//             ],
//             ...
//         ])
//     ],
//     ...
// ])

对于数组,使用 Arr::recursiveOnly

$posts = Post::with(['author', 'comments'])->get()->toArray();

$data = Arr::recursiveOnly($posts, [
    '*' => [
        'author' => [
            'name'
        ],
        'comments' => [
            '*' => [
                'body'
            ]
        ]
    ]
]);

// $data => [
//     [
//         'author' => [
//             'name' => '...'
//         ],
//         'comments' => [
//             [
//                 'body' => '...'
//             ],
//             ...
//         ]
//     ],
//     ...
// ]