Laravel CRUD | Laravel MongoDB CRUD Tutorial Example

Raviya Technical
4 min readOct 1, 2023

--

Step 1 : create db of ‘mongodb’

mongo
> use mongodb

Step 2: Setup Env variable (.env) & Config File

.env

MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=mongodb
MONGO_DB_USERNAME=
MONGO_DB_PASSWORD=

config/database.php

<?php
return [
....
'connections' => [
......
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGO_DB_HOST', 'localhost'),
'port' => env('MONGO_DB_PORT', 27017),
'database' => env('MONGO_DB_DATABASE'),
'username' => env('MONGO_DB_USERNAME'),
'password' => env('MONGO_DB_PASSWORD'),
'options' => []
],
]
]

Step 3: Install Mongo Db Package

composer require mongodb/laravel-mongodb

If not working Try This method

composer require mongodb/laravel-mongodb --ignore-platform-req=ext-mongodb

Step 4: Create A Model

php artisan make:model Article -m

app/Models/Article.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MongoDB\Laravel\Eloquent\Model;

class Article extends Model
{
use HasFactory;
protected $connection = 'mongodb';
protected $collection = 'articles';
protected $fillable = [
'name', 'detail'
];
}

Step 5: Create A Controller

 php artisan make:controller ArticleController

app/Http/Controllers/ArticleController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;

class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$articles = Article::all();
return view('articles.index', compact('articles'))
->with('i', (request()->input('page', 1) - 1) * 5);
}

/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('articles.create');
}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'detail' => 'required',
]);
Article::create($request->all());
return redirect()->route('articles.index')
->with('success', 'Article created successfully.');
}

/**
* Display the specified resource.
*
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$article = Article::find($id);
return view('articles.show', compact('article'));
}

/**
* Show the form for editing the specified resource.
*
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/

public function edit($id)
{
$article = Article::find($id);
return view('articles.edit', compact('article'));
}

/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/

public function update(Request $request, $id)
{
request()->validate([
'name' => 'required',
'detail' => 'required',
]);
$article = Article::find($id);
$article->update($request->all());
return redirect()->route('articles.index')
->with('success', 'Article updated successfully');
}

/**
* Remove the specified resource from storage.
*
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$article = Article::find($id);
$article->delete();
return redirect()->route('articles.index')
->with('success', 'Article deleted successfully');
}
}

Step 6: Create Blade Files

1) app.blade.php (If Not Exits)

2) index.blade.php

3) show.blade.php

4) form.blade.php

5) create.blade.php

6) edit.blade.php

resources/views/layouts/app.blade.php (If not exits)

<!doctype html>
<html lang="en">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<title>Laravel MongoDB CRUD Application - Raviya Technical</title>
</head>

<body>
<div class="container">
@yield('content')
</div>
</body>

</html>

resources/views/articles/index.blade.php

@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Articles</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('articles.create') }}"> Create New Article</a>
</div>
</div>
</div>

@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif

<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
@foreach ($articles as $article)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $article->name }}</td>
<td>{{ $article->detail }}</td>
<td>
<form action="{{ route('articles.destroy', $article->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('articles.show', $article->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('articles.edit', $article->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection

resources/views/articles/show.blade.php

@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2> Show Article</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('articles.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
{{ $article->name }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Details:</strong>
{{ $article->detail }}
</div>
</div>
</div>
@endsection

resources/views/articles/create.blade.php

@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Add New Article</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('articles.index') }}"> Back</a>
</div>
</div>
</div>

@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<form action="{{ route('articles.store') }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@endsectiontest

resources/views/articles/edit.blade.php

@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Article</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('articles.index') }}"> Back</a>
</div>
</div>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<form action="{{ route('articles.update', $article->_id) }}" method="POST">
@csrf
@method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $article->name }}" class="form-control"
placeholder="Name">
</div>
</div>

<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Detail:</strong>
<textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $article->detail }}</textarea>
</div>
</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
@endsection

Step 7: Add Route in web.php

routes/web.php

use App\Http\Controllers\ArticleController;

Route::resource('articles',ArticleController::class);

Step 8: Run Project

php artisan serve

http://127.0.0.1:8000/articles

--

--