Looking to hire Laravel developers? Try LaraJobs

rules maintained by rector-laravel-custom-rules

Description
Custom Rector rules for laravel
Author
Last update
2025/09/03 01:04 (dev-main)
License
Links
Downloads
65

Comments
comments powered by Disqus

Laravel Eloquent Generic Rector

Before (Missing Generic Types)

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class User extends Model
{
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }
}

After (With Generic Types)

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class User extends Model
{
    /**
     * @return BelongsTo<Company, self>
     */
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }
}

Installation

composer require rector-laravel-custom-rules/rules --dev

Configuration

Edit your rector.php file:

<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use RectorLaravelCustomRules\Rules\LaravelEloquentGenericRector;

return RectorConfig::configure()
    ->withRules([
        // Add generic type annotations for Eloquent relations
        LaravelEloquentGenericRector::class,
    ]);

Usage

Run the rector to apply the transformations:

vendor/bin/rector process

What This Rector Does

This Rector automatically adds generic type annotations to Laravel Eloquent relationship methods, improving type safety and IDE support by adding proper PHPDoc annotations like @return BelongsTo<Company, self>.