Laravel 백엔드 개발 완전 가이드

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

🛒 이커머스 API

# 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 패턴

// 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);
    }

    // ... 기타 메서드
}

Service 패턴

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);
    }
}

API 테스트

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!"

💡 Best Practices

코딩 표준

// 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,
]);

🎯 다음 단계

백엔드 개발 기초를 익혔다면:

  1. JinyPHP 패키지 - Laravel 확장 기능 활용
  2. 서버 배포 - 실제 서버 환경 구축
  3. 고급 개발 패턴 - 엔터프라이즈 개발

네비게이션


마지막 업데이트: 2025-11-19 Laravel 12 & PHP 8.4 기준