Here is a tutorial based on “Static Analysis Secrets – Laravel In Practice EP13” explaining how to use static analysis tools to improve the quality of a Laravel project.
Static analysis checks your code without running it, helping detect bugs, type errors, and bad practices early.
Common tools used in Laravel:
-
PHPStan
-
Larastan
-
Pest
-
PHPUnit
Static Analysis Secrets – Laravel Tutorial
1️⃣ Install PHPStan
Inside your Laravel project run:
composer require --dev phpstan/phpstan
Test it:
vendor/bin/phpstan analyse
PHPStan scans your PHP files and reports potential problems.
2️⃣ Install Larastan (Laravel Support)
Laravel uses many dynamic features.
Larastan helps PHPStan understand Laravel.
Install:
composer require --dev nunomaduro/larastan
Publish configuration:
vendor/bin/phpstan analyse
Create config file:
phpstan.neon
Example configuration:
includes:
- vendor/nunomaduro/larastan/extension.neon
parameters:
paths:
- app
level: 5
Levels range from 0–9.
Higher level = stricter checks.
3️⃣ Run Static Analysis
Run analysis on your Laravel app:
vendor/bin/phpstan analyse
Example output:
Method App\Http\Controllers\PostController::store()
has no return type specified.
This helps detect mistakes early.
4️⃣ Fix Common Laravel Errors
Example problem:
$user = User::find($id);
echo $user->name;
Problem: $user might be null.
Correct version:
$user = User::findOrFail($id);
echo $user->name;
Static analysis will warn you about null errors.
5️⃣ Add Type Declarations
Bad code:
function getPrice($price)
{
return $price * 2;
}
Better:
function getPrice(int $price): int
{
return $price * 2;
}
Benefits:
-
safer code
-
easier debugging
-
better IDE support
6️⃣ Use Generics for Eloquent
Larastan supports generics.
Example model relation:
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany<Post>
*/
public function posts()
{
return $this->hasMany(Post::class);
}
Now PHPStan understands the relationship.
7️⃣ Integrate with CI/CD
Run static analysis automatically in your pipeline.
Example GitHub Actions step:
- name: Run PHPStan
run: vendor/bin/phpstan analyse
Benefits:
-
catches bugs before deployment
-
keeps code quality high
8️⃣ Combine Static Analysis + Tests
Best practice:
Static Analysis + Testing
Use:
-
PHPStan
-
Pest
Example test:
php artisan test
Together they ensure:
-
code correctness
-
fewer runtime errors
Real Benefits in Large Laravel Apps
Static analysis helps detect:
✔ Null errors
✔ Wrong return types
✔ Undefined variables
✔ Invalid method calls
✔ Broken Eloquent relations
This is why many enterprise Laravel apps use PHPStan.
