Tutorial: Build a Task Reminder With Laravel and MongoDB
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
Tutorial: Build a Task Reminder With Laravel and MongoDB
Overview
In this tutorial, you can learn how to use MongoDB in a Laravel application by building a simple task reminder system. The application allows you to create, read, update, and delete tasks. Additionally, it sends email reminders for upcoming tasks based on a scheduled time.
Prerequisites
Before you begin this tutorial, ensure you have the following components installed in your development environment:
-
PHP and the [MongoDB PHP extension](https://www.mongodb.com/docs/php-library/current/get-started/#install-the-mongodb-php-extension
You must also set up a MongoDB Atlas cluster. To learn how to set up a cluster, see the Getting Started guide.
Steps
- Create a new Laravel project.
Use Composer to create a new Laravel project and navigate to the project directory:
bash
composer create-project laravel/laravel LaravelMongodbProject
cd LaravelMongodbProject
- Install the MongoDB Laravel package.
To use MongoDB in your application, you must install the Laravel MongoDB package and configure it in the config/database.php file.
Install the package by using the following command:
bash
composer require mongodb/laravel-mongodb
Tip:
If you encounter an error when you run the preceding command, ensure that the MongoDB PHP extension is installed. To learn how to install, see the [Install the MongoDB PHP extension](https://www.mongodb.com/docs/php-library/current/get-started.md#std-label-php-download-and-install step in the Get Started guide.
- Configure the database connection.
After the Laravel MongoDB package installation completes, add your MongoDB database connection to the config/database.php file to complete the configuration. Add the following MongoDB configuration to the connections array that contains configurations for other database types:
```php return [
'connections' => [
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('MONGODB_URI'),
'database' => 'task_reminder',
],
// Other connections here
],
]; ```
Your application obtains the dsn value from the .env file. Navigate to your .env file. Then, create a value for MONGODB_URI and set it to the value of your MongoDB connection string.
Tip:
To obtain your MongoDB connection string, navigate to your cluster in MongoDB Atlas. Click the Connect button and click the Drivers under Connect your application. Select “PHP” from the Driver selection menu. Copy the connection string from the dialog box. For detailed steps on how to obtain your connection string, see [Create a Connection String.](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start-connection-string
In your .env file, set the DB_CONNECTION value to mongodb to make it the default connection for your application. Edit the SESSION_DRIVER value and set it to mongodb as shown in the following code:
json
MONGODB_URI=mongodb+srv://YOUR_MONGODB_CONNECTION_STRING
DB_CONNECTION=mongodb
// Other DB_ values here ...
SESSION_DRIVER=mongodb
- Set up authentication with Laravel Breeze.
After installing and configuring your application to work with MongoDB, set up authentication. Laravel simplifies authentication implementation by providing packages such as Laravel Breeze, Laravel Fortify and Laravel Jetstream. This tutorial uses Laravel Breeze for authentication.
Install Laravel Breeze by using Composer:
bash
composer require laravel/breeze --dev
After the installation completes, run the following commands:
```bash php artisan key:generate
php artisan breeze:install php artisan migrate
php artisan db:seed npm install npm run dev ```
This prompts you to choose your preferred stack and testing package. For this tutorial, select the first option, Blade with Alpine:
text
┌ 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 │
└──────────────────────────────────────────────────────────────┘
This command adds authentication views, routes, controllers, and other related resources to your application.
- Configure the User model and authentication for MongoDB.
Laravel Breeze creates a default User model for SQL databases. You must update it to work with MongoDB and resolve rate limiting compatibility issues.
Open app/Models/User.php and replace its contents with the following:
```php <?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',
];
}
} ```
- Serve the project and test the MongoDB connection.
Serve the project by using Laravel's built-in server and confirm that everything works properly. In the Laravel project directory, run the following command:
bash
php artisan serve
The project serves at 127.0.0.1:8000. If port 8000 is already in use, Laravel switches to a new available port, which it prints to the terminal.
To test the authentication system, select the Register button in your application and create a new user account. This stores the user in your MongoDB database and allows you to log in with those credentials. For this tutorial, you can set the username to test@example.com and the password to password.
To verify that the Laravel MongoDB package was configured properly, create a route to ping your MongoDB cluster. Add the following to routes/web.php:
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];
});
Visit this route in your browser. With the correct configuration, you see the message “MongoDB is accessible!” in your browser.
- Create the task model and controller.
Create the model and controller for the task scheduling feature by using the following command:
bash
php artisan make:model Task --resource --controller
This command creates the Task model in the app/Models directory and the TaskController in the app/Http/Controllers directory with resource methods.
Create a route for the TaskController by navigating to routes/web.php and adding the following code:
```php use App\Http\Controllers\TaskController;
// Other route definitions...
Route::resource('tasks', TaskController::class)->middleware('auth'); ```
- Configure the Task model.
Navigate to app/Models/Task.php and replace the contents of the file with the following code:
```php
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.');
}
}
```
The `TaskController` class contains code that handles the CRUD operations of the task model:
- The `index()` method retrieves all tasks belonging to the logged-in user and sends them to the `index.blade.php` file for display.
- The `create()` method returns the form view for creating a new task.
- The `store()` method validates input, assigns the logged-in user's email to the task, and saves it to the database.
- The `edit()` method retrieves the specific task to be edited and displays it in an edit form.
- The `update()` method saves the edited task to the MongoDB task collection.
- The `destroy()` method deletes a specific task.
Each operation redirects back to the task list with a success message for user feedback.
10. Create view files for the task scheduler.
In the `resources/views` directory, create a folder named `tasks` and create the following files in it:
- `create.blade.php`
- `edit.blade.php`
- `index.blade.php`
Navigate to `resources/views/tasks/create.blade.php` and add the following content:
```php
{{ __('Tasks') }}
Create New Task
{{ __('Edit Task') }}
{{ __('Tasks') }}
-
@foreach ($tasks as $task)
-
{{ $task->title }} - Due: {{ $task->due_date }}
{{ $task->description }}
@endforeach
