Laravel 10 MongoDB CRUD Operation

In this comprehensive guide, I invite you to join me on a journey to master the art of performing CRUD (Create, Read, Update, Delete) operations with MongoDB within the latest and greatest Laravel framework Laravel 10.

Laravel, renowned for its elegant and developer-friendly features, continually adapts to meet the needs of modern web development. MongoDB, on the other hand, offers unmatched flexibility and scalability as a NoSQL database solution.

By uniting these two technological giants, we gain the capability to work with intricate data structures and dynamic requirements while maintaining the hallmark elegance of Laravel.

This step-by-step guide is designed to empower developers at every skill level, whether you're a newcomer or a seasoned professional. Together, we'll explore each CRUD operation in meticulous detail, providing clear and practical examples every step of the way.

By the end of our journey, you'll not only be adept at performing MongoDB CRUD operations but also well-prepared to tackle more advanced challenges, troubleshoot common issues, and write unit tests to ensure the reliability of your code.

So, without further delay, let's dive into the world of MongoDB CRUD operations in Laravel 10.

Laravel MongoDB CRUD example

Step 1: Install Laravel 10

If you haven't already created a Laravel project, you can do so using Composer. Open your terminal and run the following command.

composer create-project laravel/laravel project-name

 

Step 2: Configure MongoDB Connection

Next, you need to configure your MongoDB connection in Laravel 10. You can configure using the given link. How to Install and Setup MongoDB in Laravel 10

 

Step 3: Create MongoDB Database

Now, we will create a MongoDB database. Make sure you have installed MongoDB in your system and connect with MongoDB before starting the CRUD operation.

mongo

> use laravel_10_mongo_crud_example

> db.posts.insert( { "name": "crud example", "detail": "this is crud example details" } )

 

Step 4: Create a Migration

Now, we will create a migration for the 'posts' table using the Laravel PHP Artisan command.

php artisan make:migration create_posts_table --create=posts

After running this command, you will discover a PHP file in the 'database/migrations/' directory.

<?php 

use Illuminate\Support\Facades\Schema; 
use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreatePostsTable extends Migration { 

/** 
* Run the migrations. 
* 
* @return void */ 

public function up() 
{ 
    Schema::create('posts', function (Blueprint $table) { 
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->longText('detail')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Now, let's execute the migration using the following command.

php artisan migrate

 

 

Step 5: Add Route

In this step, we'll define a resource route in Laravel. Resource routes are a convenient way to define routes for common CRUD (Create, Read, Update, Delete) operations in your application.

Open your routes/web.php file.

Route::resource('posts', PostController::class);

 

Step 6: Adding a Controller and Model

In this step, we'll create a controller and model in Laravel to manage our resource. Controllers handle user requests and define the application's behavior, while models represent the data and database interactions for that resource.

Create a new controller by running the following Artisan command.

php artisan make:controller PostController --resource --model=Post

Now make changes to the Post.php Model.

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Post extends Model
{
    use HasFactory;
    protected $connection = 'mongodb';
	protected $collection = 'posts';

    protected $fillable = [
        'id', 'name', 'detail'
    ];
}

Then, we will update the below code to the PostController.php file.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::latest()->paginate(5);
        return view('post.index',compact('posts'))->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('post.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',
        ]);
  
        Post::create($request->all());
   
        return redirect()->route('posts.index')->with('success','Post created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return view('post.show',compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function edit(Post $post)
    {
        return view('post.edit',compact('post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        $post->update($request->all());
  
        return redirect()->route('posts.index')->with('success','Post updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();
  
        return redirect()->route('posts.index')->with('success','Post deleted successfully');
    }
}

 

Step 7: Adding Blade Files for CRUD Operations

In this step, we'll create the Blade view files needed for the CRUD (Create, Read, Update, Delete) operations of our resource in Laravel. Blade is Laravel's template engine, and it allows us to build dynamic and interactive user interfaces.

Follow these sub-steps to add Blade view files:

  1. Navigate to the resources/views directory in your Laravel project.

  2. Inside the views directory, create a folder named after your resource (e.g., "posts").

  3. Inside the resource-specific folder, create the following Blade view files:

    • index.blade.php: This file will display a list of all resource items.
    • create.blade.php: Create a new resource item form.
    • edit.blade.php: Edit an existing resource item form.
    • show.blade.php: Display details of a specific resource item.

These Blade view files will be used to render the user interface for your CRUD operations.

resources/views/posts/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 MongoDB CRUD Operation - Techsolutionstuff</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
  
<div class="container" style="margin-top: 15px;">
    @yield('content')
</div>
   
</body>
</html>

resources/views/posts/index.blade.php

@extends('post.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 10 MongoDB CRUD Operation - Techsolutionstuff</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('posts.create') }}"> Create New Post</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 ($posts as $post)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $post->name }}</td>
            <td>{{ $post->detail }}</td>
            <td>
                <form action="{{ route('posts.destroy',$post->id) }}" method="POST">
   
                    <a class="btn btn-info" href="{{ route('posts.show',$post->id) }}">Show</a>
    
                    <a class="btn btn-primary" href="{{ route('posts.edit',$post->id) }}">Edit</a>
   
                    @csrf
                    @method('DELETE')
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
  
    {!! $posts->links() !!}
      
@endsection

 

 

resources/views/posts/create.blade.php

@extends('post.layout')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Post</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Error!</strong> <br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('posts.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>
@endsection

resources/views/posts/edit.blade.php

@extends('post.layout')
   
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Post</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
            </div>
        </div>
    </div>
   
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Error!</strong> <br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
  
    <form action="{{ route('posts.update',$post->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="{{ $post->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">{{ $post->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

resources/views/posts/show.blade.php

@extends('post.layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Post</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('posts.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>
                {{ $post->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $post->detail }}
            </div>
        </div>
    </div>
@endsection

 

Step 8: Run Laravel 10 MongoDB CRUD Operations

In this step, we will run the MongoDB CRUD (Create, Read, Update, Delete) operations in Laravel 10 to interact with your data in the MongoDB database.

php artisan serve

 

Conclusion:

In this comprehensive guide, we embarked on a journey to master the art of MongoDB CRUD (Create, Read, Update, Delete) operations within the powerful and elegant Laravel 10 framework.

Along the way, we've explored the essential steps to set up, configure, and harness the potential of these two technological giants working in harmony.

In closing, we hope this guide has been an invaluable resource in your quest to become a proficient Laravel 10 and MongoDB developer. May your web applications flourish and your coding skills continue to soar.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS