Preview:
# Laravel, php, vuejs, html, nodejs, javascript, jquery Professional Development Guidelines

## Project Setup

### Stack Preference
- **Framework**: Laravel 11+
- **PHP**: 8.3+
- **Database**: MySQL 8.0+ / PostgreSQL 15+
- **Cache**: Redis
- **Queue**: Redis Horizon
- **Frontend**: Vue.js 3 + Vite / Inertia.js (when SPA needed)
- **Testing**: Pest PHP + PHPUnit

### Project Creation Standards
```bash
composer create-project laravel/laravel project-name
cd project-name
composer require --dev pestphp/pest pestphp/pest-plugin-laravel
php artisan pest:install
```

## Code Style & Conventions

### PHP Standards
- Follow PSR-12 coding standards
- Use strict types: `declare(strict_types=1);`
- Type declarations for all method parameters and return types
- Use readonly classes for DTOs and value objects
- Prefer named arguments for clarity

### File Organization
```
app/
├── Actions/          # Business logic actions
├── DTOs/            # Data Transfer Objects
├── Enums/           # Backed enums
├── Events/          # Domain events
├── Listeners/       # Event listeners
├── Mail/            # Mail classes
├── Models/          # Eloquent models
├── Observers/       # Model observers
├── Policies/        # Authorization policies
├── Providers/       # Service providers
├── Rules/           # Custom validation rules
├── Services/        # External service integrations
├── Traits/          # Reusable traits
└── ValueObjects/    # Value objects
```

## Database & Eloquent

### Models
- Use factory pattern for test data
- Define all relationships explicitly
- Use `$fillable` instead of `$guarded`
- Add proper casts for dates and custom types
- Use query scopes for reusable queries
- Implement API Resources for transformations

### Migrations
- Use descriptive migration names
- Always define `down()` method
- Use `Schema::create()` with `id()` as first column
- Add proper indexes for foreign keys and search columns
- Document complex migrations with comments

### Example Model
```php
<?php

declare(strict_types=1);

namespace App\Models;

use App\Enums\UserStatus;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

final class User extends Model
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'email',
        'password',
        'status',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'status' => UserStatus::class,
        ];
    }

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    public function scopeActive($query): void
    {
        $query->where('status', UserStatus::ACTIVE);
    }
}
```

## Controllers & API

### Controller Standards
- Use resource controllers for CRUD
- Use Form Request classes for validation
- Use API Resources for responses
- Implement proper error handling
- Return consistent JSON structures
- Use route model binding

### API Versioning
- Prefix routes with `/api/v1/`
- Use API Resources for transformations
- Implement proper pagination
- Use ETags for caching

### Example Controller
```php
<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class UserController extends Controller
{
    public function index(): AnonymousResourceCollection
    {
        return UserResource::collection(
            User::query()->paginate(15)
        );
    }

    public function store(StoreUserRequest $request): JsonResponse
    {
        $user = User::create($request->validated());

        return response()->json([
            'data' => new UserResource($user),
            'message' => 'User created successfully',
        ], 201);
    }
}
```

## Testing

### Pest PHP Standards
- Use `it()` for feature tests
- Use `test()` for unit tests
- Follow AAA pattern (Arrange, Act, Assert)
- Test one thing per test
- Use factories for test data
- Mock external services

### Example Test
```php
<?php

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('creates a new user', function () {
    $userData = [
        'name' => 'John Doe',
        'email' => 'john@example.com',
        'password' => 'password123',
    ];

    $response = $this->postJson('/api/v1/users', $userData);

    $response->assertStatus(201)
        ->assertJsonPath('data.name', 'John Doe');

    $this->assertDatabaseHas('users', [
        'email' => 'john@example.com',
    ]);
});
```

## Security

### Requirements
- Use Laravel Sanctum for API authentication
- Implement rate limiting
- Use CSRF protection for web routes
- Validate all user inputs
- Use prepared statements (Eloquent handles this)
- Hash passwords with bcrypt
- Implement proper authorization with Policies

## Performance

### Best Practices
- Use eager loading to prevent N+1 queries
- Cache expensive operations
- Use queue for background jobs
- Optimize database queries
- Use Redis for sessions and cache
- Enable OPcache in production

## Environment Configuration

### Required .env Variables
```env
APP_NAME=
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=

CACHE_DRIVER=redis
QUEUE_CONNECTION=redis
SESSION_DRIVER=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME="${APP_NAME}"
```

## Git & Deployment

### Git Standards
- Feature branch workflow
- Conventional Commits for messages
- PR reviews required
- CI/CD pipeline with tests

### Deployment Checklist
- [ ] Run migrations: `php artisan migrate --force`
- [ ] Clear cache: `php artisan optimize:clear`
- [ ] Build assets: `npm run build`
- [ ] Configure supervisor for queues
- [ ] Set up SSL/HTTPS
- [ ] Configure monitoring (Sentry, LogRocket)

## Documentation

### Requirements
- README with setup instructions
- API documentation with OpenAPI/Swagger
- Inline comments for complex logic
- PHPDoc for public methods

---

## Qwen Code Personality & Behavior

### Einstein Mindset
When assisting with Laravel development, embody the following principles:

1. **Relentless Precision** - "God does not play dice with the universe." Never accept sloppy code. Always identify and correct errors, anti-patterns, and potential bugs.

2. **Deep Curiosity** - Question assumptions. Ask "why" before "how". Understand the problem fully before proposing solutions.

3. **Simplicity Through Intelligence** - "Everything should be made as simple as possible, but not simpler." Refactor complex solutions into elegant, maintainable code.

4. **Teaching Mentality** - Explain the reasoning behind corrections. Help the user understand *why* something is wrong, not just *what* is wrong.

5. **Perfectionist Standards** - 
   - Never provide code you wouldn't deploy to production
   - Always suggest tests for new functionality
   - Point out security vulnerabilities immediately
   - Optimize for readability, maintainability, AND performance
   - Catch edge cases before they become bugs

6. **Constructive Criticism** - When you see an error or suboptimal approach:
   - Point it out clearly and directly
   - Explain the potential consequences
   - Provide the corrected solution with reasoning
   - Suggest better alternatives when they exist

7. **First Principles Thinking** - Break down complex problems to their fundamental truths. Build solutions from the ground up based on solid foundations.

### Response Guidelines
- **Be proactive**: Anticipate problems before the user encounters them
- **Be thorough**: Don't skip steps or make assumptions
- **Be educational**: Every interaction should teach something valuable
- **Be honest**: If something is wrong, say it. If you're uncertain, admit it.
- **Be excellent**: Mediocrity is not acceptable. Strive for genius-level solutions.

---

**Note to Qwen Code**: When helping with Laravel projects, always follow these guidelines. Suggest best practices, enforce type safety, and recommend testing for all new features. Channel Einstein's pursuit of perfection and deep understanding in every response.
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter