PHP code example of amrachraf6699 / laravel-nplusone-scanner

1. Go to this page and download the library: Download amrachraf6699/laravel-nplusone-scanner 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/ */

    

amrachraf6699 / laravel-nplusone-scanner example snippets


$users = User::all();

foreach ($users as $user) {
    echo $user->posts->count();
}

$users = User::with('posts')->get();

foreach ($users as $user) {
    echo $user->posts->count();
}

$users = User::all();

foreach ($users as $user) {
    $count = $user->posts()->count();
}

$users = User::withCount('posts')->get();
$users = User::withExists('posts')->get();

User::all()->map(fn ($user) => $user->posts->count());

User::with('posts')->get()
    ->each(fn ($user) => $user->posts->count());

/** @mixin \App\Models\User */
class UserResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'posts' => PostResource::collection($this->posts),
        ];
    }
}

'posts' => PostResource::collection(
    $this->whenLoaded('posts')
),

$users = User::all();

for ($i = 0; $i < 100; $i++) {
    echo $users[$i]->posts->count();
}

$user = User::first();

while ($running) {
    echo $user->posts->count();
    $running = false;
}

User::with('posts')->get();
User::query()->with(['posts', 'profile'])->get();
User::with('posts.comments')->get();
$users->load('posts');
$users->loadMissing('posts');

$users = User::withCount('posts')->get();

foreach ($users as $user) {
    echo $user->posts_count; // safe aggregate attribute
    echo $user->posts;       // still a relationship access candidate
}



return [
    'paths' => ['app'],
    'metadata_paths' => ['app'],
    'exclude' => [
        'vendor',
        'storage',
        'bootstrap/cache',
    ],
    'rules' => [
        'N1' => true,
        'N2' => true,
        'N3' => true,
        'N4' => true,
    ],
    'minimum_severity' => 'low',
    'resource_models' => [],
    'additional_rules' => [],
];

'resource_models' => [
    App\Http\Resources\UserResource::class => App\Models\User::class,
],

$relation = $request->string('relation');
$user->{$relation}; // relationship identity is unknown

abstract class BaseModel extends Model {}

class User extends BaseModel
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}
bash
php artisan vendor:publish --tag=nplusone-config
bash
php artisan nplusone:scan
bash
php artisan nplusone:scan --path=app/Http --path=app/Services
bash
php artisan vendor:publish --tag=nplusone-config
bash
php benchmarks/generate-fixtures.php .tmp/fixtures 1000