PHP code example of naotake51 / laravel-recursive-only

1. Go to this page and download the library: Download naotake51/laravel-recursive-only library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

naotake51 / laravel-recursive-only example snippets


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

class Post extends Model implements HasRecursiveOnly
{
    use 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' => '...'
//             ],
//             ...
//         ])
//     ],
//     ...
// ])

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

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

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