Hello, laravel web developers! In this article, we'll see how to create Laravel 11 API with MongoDB database. In laravel 11, we'll create an API. Also, we'll use the MongoDB database. Here, we'll install mongodb/laravel-mongodb composer package.
MongoDB is built on a scale-out architecture that has become popular with developers of all kinds for developing scalable applications with evolving data schemas.
As a document database, MongoDB makes it easy for developers to store structured or unstructured data. It uses a JSON-like format to store documents.
Create Laravel 11 API with MongoDB Database
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-example
Then, we'll install the Mongo driver using the following command.
sudo pecl install mongodb
Insert the extension in the php.ini
file under the dynamic extensions.
extension="mongodb.so"
Install the MongoDB package using the following command.
composer require mongodb/laravel-mongodb:version
Next, we'll configure the .env file.
DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
# DB_HOST=db
DB_PORT=27017
DB_DATABASE=laravelmongo
DB_USERNAME=
DB_PASSWORD=
DB_URI=mongodb://admin:admin@0.0.0.0:27017/laraveltodos
Then, we'll configure a database in the database.php file.
app/config/database.php
'default' => env('DB_CONNECTION', 'mongodb')
'mongodb' => [
'driver' => env('DB_CONNECTION','mongodb'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '27017'),
'database' => env('DB_DATABASE', 'phptodos'),
'username' => env('DB_USERNAME', 'admin'),
'password' => env('DB_PASSWORD', 'admin'),
],
Next, we'll create a model and migration using the following command.
php artisan make:model Todo -a
app/models/Todo.php
<?php
namespace App\Models;
use MongoDB\Laravel\Eloquent\Model;
class Todo extends Model
{
protected $collection = 'todos';
protected $fillable = ['name', 'status'];
protected $casts = ["id" => "string"];
}
Create a new file for the responses that will be generated from the API. In the app/Models folder create a new file
touch TodoResponse.php
app/Models/TodoResponse.php
<?php
namespace App\Models;
class TodoResponse
{
public bool $success;
public string $message;
public $payload;
public function __construct(bool $success, string $message, $payload)
{
$this->success = $success;
$this->message = $message;
$this->payload = $payload;
}
public function to_json()
{
$res = [
"success" => $this->success,
"message" => $this->message,
"payload" => $this->payload
];
return $res;
}
}
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('todos', function (Blueprint $table) {
$table->string("name");
$table->boolean("status");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('todos');
}
};
Then, migrate the table into the database using the following command.
php artisan migrate
Now, open TodoController.php file and add the following code to that file.
app/Http/Controllers/TodoController.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Todo;
use App\Models\TodoResponse;
// use Ramsey\Uuid\Uuid;
class TodoController extends Controller
{
public function index()
{
try {
$todos = Todo::orderBy("updated_at", "desc")->get();
$res = new TodoResponse(true, "Got todos", $todos);
return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
} catch (\Exception $e) {
echo $e;
$res = new TodoResponse(false, "Invalid request", $e->getMessage());
return response($res->to_json(), 500, ["Content-Type" => "application/json"]);
}
}
public function store()
{
try {
$todo = new Todo();
$todo->name = request("name");
$todo->status = request("status");
$data = $todo->save();
if (!$data) {
$res = new TodoResponse(false, "Invalid request", null);
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
$res = new TodoResponse(true, "Created todo", $todo);
return response($res->to_json(), 201, ["Content-Type" => "application/json"]);
} catch (\Exception $e) {
$res = new TodoResponse(false, "Invalid request", $e->getMessage());
return response($res->to_json(), 500, ["Content-Type" => "application/json"]);
}
}
public function show($id)
{
try {
$todo = Todo::query()->where("_id", "=", $id)->get();
if (!count($todo)) {
$res = new TodoResponse(false, "Invalid request", null);
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
$res = new TodoResponse(true, "Got todo", $todo);
return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
} catch (\Exception $e) {
$res = new TodoResponse(false, "Invalid request", $e->getMessage());
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
}
public function update($id)
{
try {
$todo = Todo::query()->where("_id", "=", $id)->get();
if (!count($todo)) {
$res = new TodoResponse(false, "Invalid request", null);
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
$updated_todo = new Todo();
$updated_todo->name = request("name");
$updated_todo->status = request("status");
$result = Todo::query()->where("_id", "=", $id)->update([
'name' => $updated_todo->name,
'status' => $updated_todo->status
]);
if (!$result) {
$res = new TodoResponse(false, "Invalid request", null);
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
$res = new TodoResponse(true, "Updated todo", $updated_todo);
return response($res->to_json(), 201, ["Content-Type" => "application/json"]);
} catch (\Exception $e) {
$res = new TodoResponse(false, "Invalid request", $e->getMessage());
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
}
public function delete($id)
{
try {
$todo = Todo::query()->where('_id', "=", $id);
if (!count($todo->get())) {
$res = new TodoResponse(false, "Invalid request", null);
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
$result = $todo->delete();
if (!$result) {
$res = new TodoResponse(false, "Invalid request", null);
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
$res = new TodoResponse(true, "Deleted todo", $todo);
return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
} catch (\Exception $e) {
$res = new TodoResponse(false, "Invalid request", $e->getMessage());
return response($res->to_json(), 400, ["Content-Type" => "application/json"]);
}
}
}
Now, define the routes into the api.php file.
routes/api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TodoController;
use App\Models\TodoResponse;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get("/v1", function () {
$res = new TodoResponse(true, "Message received", null);
return response($res->to_json(), 200, ["Content-Type" => "application/json"]);
});
Route::get("/v1/todos", [TodoController::class, "index"])->name("todos.index");
Route::get("/v1/todos/{id}", [TodoController::class, "show"])->name("todos.show");
Route::post("/v1/todos", [TodoController::class, "store"])->name("todos.store");
Route::put("/v1/todos/{id}", [TodoController::class, "update"])->name("todos.update");
Route::delete("/v1/todos/{id}", [TodoController::class, "delete"])->name("todos.delete");
Open the Handler.php file in the app/Exceptions folder.
app/Exceptions/Handler.php
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('*')) {
return response()->json([
'success' => false,
'message' => 'Invalid route',
'payload' => null
], 404);
}
});
}
The file will need to have the following import to work properly
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like: