개요
이 튜토리얼에서는 간단한 작업 알림 시스템을 구축하여 Laravel 애플리케이션 에서 MongoDB 사용하는 방법을 학습 수 있습니다. 이 애플리케이션 사용하면 작업을 만들고, 읽고, 업데이트, 삭제 수 있습니다. 또한 예약된 시간을 기준으로 예정된 작업에 대한 이메일 알림을 보냅니다.
전제 조건
이 튜토리얼을 시작하기 전에 개발 환경에 다음 구성 요소가 설치되어 있는지 확인하세요.
MongoDB Atlas cluster 도 설정하다 해야 합니다. 클러스터 설정하다 방법을 학습하려면 빠른 시작 가이드를 참조하세요.
단계
MongoDB Laravel 패키지 설치합니다.
애플리케이션 에서 MongoDB 사용하려면 Laravel MongoDB 패키지 설치하고 config/database.php 파일 에 구성해야 합니다.
다음 명령을 사용하여 패키지 설치합니다.
composer require mongodb/laravel-mongodb
팁
앞의 명령을 실행 때 오류가 발생하면 MongoDB PHP 확장이 설치되어 있는지 확인합니다. 설치 방법을 학습하려면 시작하기 가이드에서 MongoDB PHP 확장 설치 단계를 참조하세요.
데이터베이스 연결을 구성합니다.
Laravel MongoDB 패키지 설치가 완료된 후 config/database.php 파일 에 MongoDB 데이터베이스 연결을 추가하여 구성을 완료합니다. 다른 데이터베이스 유형에 대한 구성이 포함된 connections 배열 에 다음 MongoDB 구성을 추가합니다.
return [ 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => env('MONGODB_URI'), 'database' => 'task_reminder', ], // Other connections here ], ];
애플리케이션 은 .env 파일 에서 dsn 값을 가져옵니다. .env 파일 로 이동합니다. 그런 다음 MONGODB_URI 에 대한 값을 생성하고 이를 MongoDB 연결 문자열 의 값으로 설정하다 .
팁
MongoDB 연결 문자열 얻으려면 MongoDB Atlas 에서 클러스터 로 이동합니다. Connect 버튼을 클릭하고 Connect your application 아래의 Drivers 를 클릭합니다. Driver 선택 메뉴에서 "PHP"를 선택합니다. 대화 상자에서 연결 문자열 복사합니다. 연결 문자열 가져오는 방법에 대한 자세한 단계는 연결 문자열을 참조하세요.
.env 파일 에서 DB_CONNECTION 값을 mongodb 로 설정하다 애플리케이션 의 기본값 연결로 설정합니다. 다음 코드에 표시된 대로 SESSION_DRIVER 값을 편집하고 mongodb 로 설정하다 .
MONGODB_URI=mongodb+srv://YOUR_MONGODB_CONNECTION_STRING DB_CONNECTION=mongodb // Other DB_ values here ... SESSION_DRIVER=mongodb
Laravel Breeze로 인증 설정합니다.
MongoDB 와 함께 작동하도록 애플리케이션 설치 및 구성한 후 인증 설정하다 합니다. Laravel은 Laravel Breeze, Laravel Fortify 및 Laravel Jetstream과 같은 패키지를 제공하여 인증 구현 간소화합니다. 이 튜토리얼에서는 인증에 Laravel Breeze 를 사용합니다.
컴포저를 사용하여 Laravel Breeze를 설치합니다.
composer require laravel/breeze --dev
설치가 완료되면 다음 명령을 실행 .
php artisan key:generate php artisan breeze:install php artisan migrate php artisan db:seed npm install npm run dev
원하는 스택 및 테스트 패키지 선택하라는 메시지가 표시됩니다. 이 튜토리얼에서는 첫 번째 옵션인 Blade with Alpine을 선택합니다.
┌ Which Breeze stack would you like to install? ───────────────┐ │ > ● Blade with Alpine │ │ ○ Livewire (Volt Class API) with Alpine │ │ ○ Livewire (Volt Functional API) with Alpine │ │ ○ React with Inertia │ │ ○ Vue with Inertia │ │ ○ API only │ └──────────────────────────────────────────────────────────────┘
이 명령은 인증 보기, 경로, 컨트롤러 및 기타 관련 리소스를 애플리케이션 에 추가합니다.
MongoDB 에 대한 사용자 모델 및 인증 구성합니다.
Laravel Breeze는 SQL 데이터베이스에 대한 기본값 사용자 모델을 생성합니다. MongoDB 와 함께 작동하고 속도 제한 호환성 문제를 해결하려면 업데이트 해야 합니다.
app/Models/User.php 를 열고 해당 내용을 다음으로 바꿉니다.
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Notifications\Notifiable; use MongoDB\Laravel\Auth\User as MongoUser; class User extends MongoUser { use HasFactory, Notifiable; protected $connection = 'mongodb'; protected $collection = 'users'; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get the attributes to cast. * * @return array<string, string> */ protected function casts(): array { return [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; } }
프로젝트 제공하고 MongoDB 연결을 테스트합니다.
Laravel의 내장 서버 사용하여 프로젝트 제공하고 모든 것이 제대로 작동하는지 확인합니다. Laravel 프로젝트 디렉토리 에서 다음 명령을 실행 .
php artisan serve
프로젝트 는 127.0.0.1:8000에서 제공됩니다. 포트 8000 이 이미 사용 중인 경우 Laravel은 사용 가능한 새 포트로 전환하여 터미널에 출력합니다.
인증 시스템을 테스트하려면 애플리케이션 에서 Register 버튼을 선택하고 새 사용자 계정을 만듭니다. 이렇게 하면 사용자가 MongoDB 데이터베이스 에 저장되고 해당 자격 증명 으로 로그인 할 수 있습니다. 이 튜토리얼에서는 사용자 이름 test@example.com 로, 비밀번호를 password로 설정하다 수 있습니다.
Laravel MongoDB 패키지 올바르게 구성되었는지 확인하려면 MongoDB 클러스터 핑 하는 경로를 생성합니다. routes/web.php에 다음을 추가합니다.
Route::get('/ping', function (Request $request) { $connection = DB::connection('mongodb'); try { $connection->command(['ping' => 1]); $msg = 'MongoDB is accessible!'; } catch (\MongoDB\Driver\Exception\ConnectionException $e) { $msg = 'You are not connected to MongoDB. Error: ' . $e->getMessage(); } return ['msg' => $msg]; });
브라우저에서 이 경로를 방문합니다. 올바른 구성을 사용하면 "MongoDB 에 액세스할 수 있습니다!" 브라우저에서.
작업 모델과 컨트롤러를 만듭니다.
다음 명령을 사용하여 작업 예정 기능 에 대한 모델 및 컨트롤러를 생성합니다.
php artisan make:model Task --resource --controller
이 명령은 리소스 메서드를 사용하여 app/Models 디렉토리 에 Task 모델을 생성하고 app/Http/Controllers 디렉토리 에 TaskController 를 생성합니다.
routes/web.php 로 이동하여 다음 코드를 추가하여 TaskController 에 대한 경로를 생성합니다.
use App\Http\Controllers\TaskController; // Other route definitions... Route::resource('tasks', TaskController::class)->middleware('auth');
작업 모델을 구성합니다.
app/Models/Task.php 로 이동하여 파일 의 내용을 다음 코드로 바꿉니다.
namespace App\Models; use MongoDB\Laravel\Eloquent\Model; class Task extends Model { protected $connection = 'mongodb'; protected $table = 'tasks'; protected $fillable = [ 'title', 'description', 'due_date', 'email', 'reminder_time', 'last_notification_date' ]; }
이 코드는 다음 사양으로 작업 모델을 생성합니다.
네임스페이스 뒤의
use MongoDB\Laravel\Eloquent\Model성명서 MongoDB 모델에만 해당됩니다. MongoDB 쿼리를 사용하여 SQL 로 구현된 Eloquent 기능을 재정의합니다.protected $table = 'tasks'속성 선택 사항입니다. 이 모델의 문서를 저장 데 사용되는 MongoDB 컬렉션 의 이름을 지정합니다.protected $fillable속성 대량 할당 가능한 속성을 지정합니다.
팁
MongoDB 의 고유한 기능 중 하나는 관계형 데이터베이스와 같은 마이그레이션이 필요하지 않다는 것입니다. 모델을 업데이트하거나 마이그레이션을 만들지 않고도 문서에 직접 새 필드를 추가할 수 있습니다. 이 기능 동적 데이터를 처리할 때 유용합니다.
Taskcontroller 로직을 생성합니다.
app/Http/Controllers/TaskController.php (으)로 이동하여 다음 코드로 콘텐츠를 업데이트 .
namespace App\Http\Controllers; use App\Models\Task; use Carbon\Carbon; use Illuminate\Http\Request; class TaskController extends Controller { /** * Displays a listing of the resource. */ public function index() { $tasks = Task::where('email', auth()->user()->email)->get(); return view('tasks.index', compact('tasks')); } /** * Shows the form for creating a new resource. */ public function create() { return view('tasks.create'); } /** * Stores a newly created resource in storage. */ public function store(Request $request) { $data = $request->validate([ 'title' => 'required|string|max:255', 'description' => 'nullable|string', 'due_date' => 'required|date', 'reminder_time' => 'required|date', ]); $data['due_date'] = Carbon::parse($request->due_date); $data['reminder_time'] = Carbon::parse($request->reminder_time); $data['email'] = auth()->user()->email; $data['last_notification_date'] = null; Task::create($data); return redirect()->route('tasks.index')->with('success', 'Task created successfully.'); } /** * Displays the specified resource. */ public function show(string $id) { // } /** * Shows the form for editing the specified resource. */ public function edit(string $id) { $tasks = Task::where('id', $id)->get(); return view('tasks.edit', ['tasks' => $tasks]); } /** * Updates the specified resource in storage. */ public function update(Request $request, string $id) { $data = $request->validate([ 'title' => 'required|string|max:255', 'description' => 'nullable|string', 'due_date' => 'required|date', 'reminder_time' => 'required|date', ]); $task = Task::findOrFail($id); $data['due_date'] = Carbon::parse($request->due_date)->format('Y-m-d H:i:s'); $data['reminder_time'] = Carbon::parse($request->reminder_time)->format('Y-m-d H:i:s'); $task->update($data); return redirect()->route('tasks.index')->with('success', 'Task updated successfully.'); } /** * Removes the specified resource from storage. */ public function destroy(string $id) { $task = Task::findOrFail($id); $task->delete(); return redirect()->route('tasks.index')->with('success', 'Task deleted successfully.'); } }
TaskController 클래스에는 작업 모델의 CRUD 작업을 처리하는 코드가 포함되어 있습니다.
index()메서드는 로그인한 사용자에게 속한 모든 작업을 검색하여 표시할index.blade.php파일 로 보냅니다.create()메서드는 새 작업 만들기 위한 양식 보기를 반환합니다.store()메서드는 입력의 유효성을 검사하고, 로그인한 사용자의 이메일 작업 에 할당한 다음 데이터베이스 에 저장합니다.edit()메서드는 편집할 특정 작업 검색하여 편집 양식에 표시합니다.update()메서드는 편집한 작업 MongoDB 작업 컬렉션 에 저장합니다.destroy()메서드는 특정 작업 삭제합니다.
각 작업은 사용자 피드백 에 대한 성공 메시지와 함께 작업 목록으로 다시 리디렉션됩니다.
작업 스케줄러에 대한 보기 파일을 만듭니다.
resources/views 디렉토리 에 tasks 라는 이름의 폴더를 만들고 그 안에 다음 파일을 만듭니다.
create.blade.phpedit.blade.phpindex.blade.php
resources/views/tasks/create.blade.php (으)로 이동하여 다음 콘텐츠를 추가합니다.
1 <x-app-layout> 2 <x-slot name="header"> 3 <h2 class="font-semibold text-xl text-gray-800 leading-tight"> 4 {{ __('Tasks') }} 5 </h2> 6 </x-slot> 7 8 <div class="py-12"> 9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> 10 <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> 11 <div class="container mx-auto p-4"> 12 <h2 class="text-2xl font-bold mb-4">Create New Task</h2> 13 14 <form action="{{ route('tasks.store') }}" method="POST"> 15 @csrf 16 17 <div class="mb-4"> 18 <label for="title" class="block text-gray-700">Title:</label> 19 <input type="text" 20 name="title" 21 id="title" 22 required 23 class="border border-gray-300 p-2 w-full" 24 value="{{ old('title') }}"> 25 @error('title') 26 <p class="text-red-500">{{ $message }}</p> 27 @enderror 28 </div> 29 30 <div class="mb-4"> 31 <label for="description" class="block text-gray-700">Description:</label> 32 <textarea name="description" 33 id="description" 34 class="border border-gray-300 p-2 w-full">{{ old('description') }}</textarea> 35 </div> 36 37 <div class="mb-4"> 38 <label for="due_date" class="block text-gray-700">Due Date:</label> 39 <input type="date" 40 name="due_date" 41 id="due_date" 42 required 43 class="border border-gray-300 p-2 w-full" 44 value="{{ old('due_date') }}"> 45 @error('due_date') 46 <p class="text-red-500">{{ $message }}</p> 47 @enderror 48 </div> 49 50 <div class="mb-4"> 51 <label for="reminder_time" class="block text-gray-700">Reminder Time:</label> 52 <input type="datetime-local" 53 name="reminder_time" 54 id="reminder_time" 55 class="border border-gray-300 p-2 w-full" 56 value="{{ old('reminder_time') }}"> 57 </div> 58 59 <button type="submit" 60 class="bg-green-600 text-white p-2 border rounded"> 61 Create Task 62 </button> 63 </form> 64 </div> 65 </div> 66 </div> 67 </div> 68 </x-app-layout>
양식에는 title 및 description 에 대한 텍스트 입력과 due date 및 reminder time에 대한 날짜 및 시간 입력이 포함되어 있습니다.
resources/views/tasks/edit.blade.php (으)로 이동하여 다음 콘텐츠를 추가합니다.
1 <x-app-layout> 2 <x-slot name="header"> 3 <h2 class="font-semibold text-xl text-gray-800 leading-tight"> 4 {{ __('Edit Task') }} 5 </h2> 6 </x-slot> 7 8 <div class="py-12"> 9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> 10 <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> 11 <div class="p-6 text-gray-900"> 12 @foreach($tasks as $task) 13 <form action="{{ route('tasks.update', $task->id) }}" method="POST"> 14 @csrf 15 @method('PUT') 16 17 <div class="mb-4"> 18 <label for="title" class="block text-gray-700">Title:</label> 19 <input type="text" 20 name="title" 21 id="title" 22 required 23 class="border border-gray-300 p-2 w-full" 24 value="{{ old('title', $task->title) }}"> 25 @error('title') 26 <p class="text-red-500">{{ $message }}</p> 27 @enderror 28 </div> 29 30 <div class="mb-4"> 31 <label for="description" class="block text-gray-700">Description:</label> 32 <textarea name="description" 33 id="description" 34 class="border border-gray-300 p-2 w-full">{{ old('description', $task->description) }}</textarea> 35 </div> 36 37 <div class="mb-4"> 38 <label for="due_date" class="block text-gray-700">Due Date:</label> 39 <input type="date" 40 name="due_date" 41 id="due_date" 42 required 43 class="border border-gray-300 p-2 w-full" 44 value="{{ old('due_date', $task->due_date) }}"> 45 @error('due_date') 46 <p class="text-red-500">{{ $message }}</p> 47 @enderror 48 </div> 49 50 <div class="mb-4"> 51 <label for="reminder_time" class="block text-gray-700">Reminder Time:</label> 52 <input type="datetime-local" 53 name="reminder_time" 54 id="reminder_time" 55 class="border border-gray-300 p-2 w-full" 56 value="{{ old('reminder_time', $task->reminder_time) }}"> 57 </div> 58 59 <button type="submit" 60 class="bg-blue-500 text-white p-2 rounded"> 61 Update Task 62 </button> 63 </form> 64 @endforeach 65 </div> 66 </div> 67 </div> 68 </div> 69 </x-app-layout>
편집 양식에는 만들기 양식과 동일한 입력 필드가 포함되어 있으며 현재 편집 중인 작업 의 데이터와 함께 로드됩니다.
resources/views/tasks/index.blade.php (으)로 이동하여 다음 콘텐츠를 추가합니다.
1 <x-app-layout> 2 <x-slot name="header"> 3 <h2 class="font-semibold text-xl text-gray-800 leading-tight"> 4 {{ __('Tasks') }} 5 </h2> 6 </x-slot> 7 8 <div class="py-12"> 9 <div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> 10 <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> 11 <div class="p-6 text-gray-900"> 12 <div class="mb-2"> 13 <a href="{{ route('tasks.create') }}" 14 class="p-2 border mb-4"> 15 Create New Task 16 </a> 17 </div> 18 19 <ul class="mt-4"> 20 @foreach ($tasks as $task) 21 <div class="mt-2"> 22 <hr> 23 </div> 24 25 <li> 26 <h1 class="text-2xl"> 27 <strong>{{ $task->title }}</strong> 28 - Due: {{ $task->due_date }} 29 </h1> 30 31 <p class="text-gray-600"> 32 {{ $task->description }} 33 </p> 34 35 <div class="flex gap-2 mt-4"> 36 <div class="p-2 text-white bg-gray-700"> 37 <a href="{{ route('tasks.edit', $task->id) }}"> 38 Edit 39 </a> 40 </div> 41 42 <div class="p-2 text-white bg-red-700 rounded"> 43 <form action="{{ route('tasks.destroy', $task->id) }}" 44 method="POST" 45 style="display:inline;"> 46 @csrf 47 @method('DELETE') 48 <button type="submit">Delete</button> 49 </form> 50 </div> 51 </div> 52 </li> 53 @endforeach 54 </ul> 55 </div> 56 </div> 57 </div> 58 </div> 59 </x-app-layout>
이 보기에는 만들기 양식에 대한 링크가 포함되어 있으며 모든 작업을 반복하여 인증된 사용자의 작업을 표시합니다.
작업에 대한 탐색 링크를 추가합니다.
애플리케이션 탐색에서 작업 기능 에 대한 링크를 추가합니다. resources/views/layouts/navigation.blade.php (으)로 고 (Go) 대시보드 탐색 링크 뒤에 다음 코드를 추가합니다.
1 // ...existing code ... 2 <div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex"> 3 <x-nav-link :href="route('tasks.index')" :active="request()->routeIs('tasks.index')"> 4 {{ __('Tasks') }} 5 </x-nav-link> 6 </div>
이 점 에서 작업 관리 시스템의 CRUD 작업을 테스트할 수 있습니다. 다음 섹션으로 이동하기 전에 모든 것이 올바르게 작동하는지 확인하세요.
미리 알림을 보내기 위한 사용자 지정 아티즌 명령을 생성합니다.
마감된 작업에 대한 알림 시스템을 구현 하려면 이메일 통해 알림을 보내는 사용자 지정 아티즌 명령을 생성하고 자동 예약에 명령을 등록합니다.
사용자 지정 아티즌 명령을 생성하려면 터미널에서 다음 코드를 실행 .
php artisan make:command SendTaskReminders
명령을 생성한 후 다음 코드로 app/Console/Commands/SendTaskReminders.php 파일 의 내용을 업데이트 .
namespace App\Console\Commands; use App\Models\Task; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\Mail; class SendTaskReminders extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'app:send-task-reminders'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Execute the console command. */ public function handle() { $now = Carbon::now(); $upcomingTasks = Task::where('last_notification_date', null)->get(); $upcomingTasks = Task::where('last_notification_date', null) ->where('reminder_time', '>=', $now->clone()->subMinutes(10)) ->get(); foreach ($upcomingTasks as $task) { $emailBody = <<<EOF Hello, This is a reminder for your task: Title: {$task->title} Description: {$task->description} Due Date: {$task->due_date} Please make sure to complete it on time! Regards, Your Task Reminder App EOF; Mail::raw($emailBody, function ($message) use ($task) { $message->to($task->email) ->subject("Task Reminder: {$task->title}"); }); $task->last_notification_date = $now; $task->save(); $this->info("Reminder email sent for task: {$task->title}"); } return self::SUCCESS; } }
사용자 지정 아티즌 명령의 기본 로직은 handle() 메서드로 작성됩니다. 이 코드는 Carbon::now()을 사용하여 현재 타임스탬프를 가져옵니다.
다음으로, 데이터베이스 쿼리하여 reminder_time 가 현재 시간보다 작거나 같은 작업과 reminder_time 가 현재 시간 10 분보다 크거나 같은 모든 작업을 가져옵니다. MongoDB 에서 모든 날짜는 UTC로 저장됩니다. 서버 다른 표준 구역 사용하더라도 구역 시간대를 변경할 필요는 없습니다.
이 쿼리 다음 10 분 이내에 마감되는 모든 작업을 가져옵니다. 이 코드는 결과를 반복하고 다음 10 분 내에 마감될 작업에 대한 알림을 사용자 이메일로 보냅니다.
참고
작업 스케줄러가 제대로 작동하려면 이메일을 보내도록 애플리케이션 구성해야 합니다. Mailtrap.io는 이메일 전송을 테스트하는 데 유용한 도구입니다. 자세히 알아보려면 Laravel에서 이메일 보내기를 참조하세요.
작업 미리 알림에 대한 알림 예약합니다.
설정 완료하려면 이전 단계에서 생성한 아티즌 명령이 매분 실행 되도록 예정 . 이 접근 방식은 1분마다 php
artisan app:send-task-reminders 를 자동으로 실행합니다.
routes/console.php (으)로 이동하여 다음 코드를 추가합니다.
// ...existing code ... Schedule::command('app:send-task-reminders')->everyMinute();
작동하는지 테스트하려면 다음 명령을 실행 .
php artisan schedule:run
프로덕션 서버 에서는 php
artisan schedule:run 명령을 정기적으로 실행 하도록 크론 작업 구성해야 합니다.
Linux 또는 Unix 기반 서버 에서는 다음 명령을 사용하여 크론 설정 파일 열 수 있습니다.
crontab -e
크론 구성 탭 에 다음 코드를 추가합니다.
* * * * * /usr/bin/php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
/usr/bin/php 을 PHP 바이너리 경로로 바꾸고 /path-to-your-project 을 서버 의 Laravel 프로젝트 의 전체 경로로 바꿉니다. 파일 저장하고 종료합니다.
크론 작업 올바르게 설정하다 되었는지 확인하려면 다음 명령을 실행 .
crontab -l
요약
이제 Laravel과 MongoDB 사용하는 작업 스케줄러 애플리케이션 생겼습니다. 이 튜토리얼에서는 다음 조치를 완료하는 방법을 설명했습니다.
MongoDB 와 함께 작동하도록 Laravel 프로젝트 구성
작업 스케줄러를 위한 CRUD 기능 구현
알림 시스템을 위한 사용자 지정 Laravel 아티즌 명령 생성
일정 간격으로 아티즌 명령을 실행 하는 작업 예약
Linux 기반 서버 에서 크론 작업 구성
다음 단계
이 튜토리얼에서 다루는 개념에 대해 자세히 학습 다음 리소스를 참조하세요.
일반적인 작업의 코드예시에 대한 사용 예시
Eloquent 모델 작업을 위한 Eloquent 모델