Laravel을 활용한 현대적인 백엔드 개발의 모든 것을 다룹니다. 기초 개념부터 실전 프로젝트까지 체계적으로 학습할 수 있습니다.
# 1. 프로젝트 생성
composer create-project laravel/laravel blog-system
cd blog-system
# 2. 기본 모델 생성
php artisan make:model Post -m
php artisan make:model Category -m
php artisan make:model Tag -m
# 3. 컨트롤러 생성
php artisan make:controller PostController --resource
# REST API 백엔드
php artisan make:controller Api/ProductController --api
php artisan make:resource ProductResource
php artisan make:request StoreProductRequest
# 관리자 시스템
php artisan make:controller Admin/DashboardController
php artisan make:middleware AdminAuth
// Repository 인터페이스
interface PostRepositoryInterface
{
public function getAllPosts();
public function getPostById($id);
public function createPost(array $data);
public function updatePost($id, array $data);
public function deletePost($id);
}
// Repository 구현
class PostRepository implements PostRepositoryInterface
{
protected $model;
public function __construct(Post $post)
{
$this->model = $post;
}
public function getAllPosts()
{
return $this->model->paginate(15);
}
// ... 기타 메서드
}
class PostService
{
protected $postRepository;
protected $imageService;
public function __construct(
PostRepositoryInterface $postRepository,
ImageService $imageService
) {
$this->postRepository = $postRepository;
$this->imageService = $imageService;
}
public function createPost(array $data)
{
// 비즈니스 로직
if (isset($data['image'])) {
$data['image_path'] = $this->imageService->upload($data['image']);
}
return $this->postRepository->createPost($data);
}
}
# 개발 도구
composer require --dev barryvdh/laravel-debugbar
composer require --dev laravel/telescope
# API 개발
composer require laravel/sanctum
composer require spatie/laravel-permission
# 유틸리티
composer require spatie/laravel-backup
composer require intervention/image
# 코드 스타일
composer require --dev friendsofphp/php-cs-fixer
# 정적 분석
composer require --dev phpstan/phpstan
composer require --dev larastan/larastan
// N+1 문제 해결
$posts = Post::with(['author', 'categories'])->get();
// 쿼리 최적화
$posts = Post::select(['id', 'title', 'slug'])
->where('published_at', '<=', now())
->orderBy('published_at', 'desc')
->paginate(10);
// 인덱스 활용
Schema::table('posts', function (Blueprint $table) {
$table->index(['published_at', 'featured']);
$table->index('slug');
});
// 모델 캐싱
class Post extends Model
{
public function getRouteKeyName()
{
return 'slug';
}
public static function findBySlug($slug)
{
return Cache::remember("post.{$slug}", 3600, function () use ($slug) {
return static::where('slug', $slug)->firstOrFail();
});
}
}
class PostTest extends TestCase
{
use RefreshDatabase;
public function test_can_create_post()
{
$user = User::factory()->create();
$postData = [
'title' => 'Test Post',
'content' => 'This is a test post.',
'user_id' => $user->id,
];
$response = $this->actingAs($user)
->post('/posts', $postData);
$response->assertStatus(201);
$this->assertDatabaseHas('posts', $postData);
}
}
class PostApiTest extends TestCase
{
public function test_can_get_posts_via_api()
{
Post::factory()->count(5)->create();
$response = $this->getJson('/api/posts');
$response->assertStatus(200)
->assertJsonStructure([
'data' => [
'*' => ['id', 'title', 'content', 'created_at']
]
]);
}
}
# 프로덕션 설정
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com
# 성능 최적화
QUEUE_CONNECTION=redis
CACHE_DRIVER=redis
SESSION_DRIVER=redis
# 로깅
LOG_CHANNEL=stack
LOG_LEVEL=warning
#!/bin/bash
# deploy.sh
echo "Starting deployment..."
# 의존성 업데이트
composer install --no-dev --optimize-autoloader
# 캐시 최적화
php artisan config:cache
php artisan route:cache
php artisan view:cache
# 마이그레이션
php artisan migrate --force
# 권한 설정
chmod -R 755 storage bootstrap/cache
echo "Deployment completed!"
// PSR-12 표준 준수
class PostController extends Controller
{
public function index(): JsonResponse
{
$posts = Post::with('author')
->published()
->paginate(15);
return response()->json([
'data' => PostResource::collection($posts),
'meta' => [
'total' => $posts->total(),
'per_page' => $posts->perPage(),
],
]);
}
}
// 커스텀 로그 채널
'channels' => [
'api' => [
'driver' => 'daily',
'path' => storage_path('logs/api.log'),
'level' => 'info',
'days' => 30,
],
],
// 사용법
Log::channel('api')->info('API 요청', [
'user_id' => auth()->id(),
'endpoint' => request()->fullUrl(),
'response_time' => $responseTime,
]);
백엔드 개발 기초를 익혔다면:
네비게이션
| 마지막 업데이트: 2025-11-19 | Laravel 12 & PHP 8.4 기준 |