laravel
Build PHP web applications with Laravel: routing, Eloquent ORM, Blade, migrations, validation, and deployment. Use for PHP backends.
Laravel
Building robust PHP web applications with Laravel.
Quick Start
composer create-project laravel/laravel my-app
cd my-app && php artisan serve
# http://localhost:8000When to Use
- PHP monoliths with clean MVC structure
- CRUD apps needing rapid development
- Teams wanting batteries-included tooling
- Projects with Blade templates or JSON APIs
Best Practices
Structure
- Follow the app structure: controllers, models, services
- Keep controllers thin; business logic in services/actions
- Use route-model binding for resourceful routes
- Organize by feature when it grows
Eloquent & Migrations
- Define migrations for every schema change
- Use Eloquent relationships and eager loading
- Add indexes; avoid N+1 queries
- Use form requests for validation
Validation & Errors
- Validate with Form Requests
- Return consistent JSON error shapes for APIs
- Handle exceptions centrally
- Use proper HTTP status codes
Security & Performance
- Use Blade escaping to prevent XSS
- Mass assignment: whitelist fillable fields
- Cache hot queries and views
- Queue heavy jobs
Dependencies
composer create-project laravel/laravel my-app
php artisan serveExamples
// routes/web.php
Route::get('/users/{user}', [UserController::class, 'show']);
// app/Http/Controllers/UserController.php
class UserController extends Controller
{
public function show(User $user)
{
return view('users.show', ['user' => $user]);
}
}// Migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('created_at')->nullable();
});// Model with relationship and fillable
class User extends Authenticatable
{
protected $fillable = ['name', 'email'];
protected $hidden = ['password'];
public function posts()
{
return $this->hasMany(Post::class);
}
}// Form request validation
class StoreUserRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
];
}
}Step-by-Step
1. Scaffold with `composer create-project`.
2. Configure DB and set up the environment.
3. Create migrations and Eloquent models.
4. Build routes and controllers.
5. Add Form Requests for validation.
6. Write Blade templates or JSON API responses.
7. Add auth, caching, and queues.
8. Test with Pest/PHPUnit and deploy.
Validation
1. `php artisan test` passes
2. Migrations apply cleanly
3. Validation rejects bad input
4. No obvious N+1 in key routes
5. App runs in production mode
Troubleshooting
- N+1: use `with()` eager loading.
- Mass assignment: set `$fillable` correctly.
- Slow responses: cache queries and views, queue jobs.
Laravel (Ларавел)
Создание надёжных PHP-веб-приложений на Laravel.
Быстрый старт
composer create-project laravel/laravel my-app
cd my-app && php artisan serve
# http://localhost:8000Когда использовать
- PHP-монолиты с чистой MVC-структурой
- CRUD-приложения с быстрой разработкой
- Команды, которым нужен полный тулинг
- Проекты с Blade-шаблонами или JSON API
Лучшие практики
Структура
- Следуйте структуре приложения: controllers, models, services
- Контроллеры тонкие; логика — в сервисах/actions
- Route-model binding для resourceful маршрутов
- По фичам, когда проект растёт
Eloquent и миграции
- Миграции на каждое изменение схемы
- Eloquent relationships и eager loading
- Индексы; избегайте N+1
- Валидация через Form Requests
Валидация и ошибки
- Валидируйте через Form Requests
- Консистентные JSON-ошибки для API
- Централизованная обработка исключений
- Корректные HTTP статус-коды
Безопасность и производительность
- Blade escaping против XSS
- Mass assignment: whitelist fillable
- Кэш горячих запросов и вьюх
- Тяжёлые задачи — в очередь
Зависимости
composer create-project laravel/laravel my-app
php artisan serveПримеры
// routes/web.php
Route::get('/users/{user}', [UserController::class, 'show']);
// app/Http/Controllers/UserController.php
class UserController extends Controller
{
public function show(User $user)
{
return view('users.show', ['user' => $user]);
}
}// Миграция
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->timestamp('created_at')->nullable();
});// Модель со связью и fillable
class User extends Authenticatable
{
protected $fillable = ['name', 'email'];
protected $hidden = ['password'];
public function posts()
{
return $this->hasMany(Post::class);
}
}// Валидация через Form Request
class StoreUserRequest extends FormRequest
{
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
];
}
}Пошаговое руководство
1. Скаффолд через `composer create-project`.
2. Настройте БД и окружение.
3. Создайте миграции и Eloquent-модели.
4. Соберите маршруты и контроллеры.
5. Добавьте Form Requests для валидации.
6. Напишите Blade-шаблоны или JSON API.
7. Добавьте auth, кэш и очереди.
8. Тестируйте Pest/PHPUnit и деплойте.
Валидация
1. `php artisan test` проходит
2. Миграции применяются чисто
3. Валидация отклоняет плохой ввод
4. Нет явных N+1 в ключевых маршрутах
5. Приложение работает в production-режиме
Устранение неполадок
- N+1: используйте `with()` eager loading.
- Mass assignment: корректно задавайте `$fillable`.
- Медленные ответы: кэшируйте запросы и вьюхи, ставьте задачи в очередь.