/

August 6, 2024

Exploring Laravel and MongoDB Integration: A Comprehensive Guide

Integrating Laravel with MongoDB offers a flexible and scalable solution for database management. Leveraging Laravel’s Eloquent ORM and MongoDB’s document-oriented approach, developers can create high-performance applications capable of handling complex data structures efficiently. With seamless compatibility between Laravel and MongoDB, developers can harness the power of both technologies to build robust and dynamic web applications.

1. Create Database MongoDB:

First we need to create a database in MongoDB named “laravel_mongo_test_db.”

2. Install Laravel Project:

composer create-project --prefer-dist laravel/laravel exampleapp

3. Database Configuration:

Put code .env file

DB_CONNECTION=mongodb

DB_DATABASE=laravel_mongo_test_db

DB_USERNAME=

DB_PASSWORD=

Now, let’s proceed to incorporate array details into the database.php configuration file following this approach.


<?php

namespace AppWidgets;

use IlluminateSupportFacadesAuth;
use IlluminateSupportStr;
use TCGVoyagerFacadesVoyager;
use TCGVoyagerWidgetsBaseDimmer;

class Product extends BaseDimmer
{
    /**
     * The configuration array.
     *
     * @var array
     */
    protected $config = [];

    /**
     * Treat this method as a controller action.
     * Return view() or other content to display.
     */
    public function run()
    {
        $count = Voyager::model('Product')->count();
        $string = trans_choice('Product', $count);

        return view('voyager::dimmer', array_merge($this->config, [
            'icon'   => 'voyager-news',
            'title'  => "{$count} {$string}",
            'text'   => __('voyager::dimmer.post_text', ['count' => $count, 'string' => Str::lower($string)]),
            'button' => [
                'text' => __('voyager::dimmer.post_link_text'),
                'link' => "#",
            ],
            'image' => voyager_asset('images/widget-backgrounds/02.jpg'),
        ]));
    }

    /**
     * Determine if the widget should be displayed.
     *
     * @return bool
     */
    public function shouldBeDisplayed()
    {
        return Auth::user()->can('browse', Voyager::model('Product'));
    }
}

 

4. Install MongoDB Package:

In this step, we’ll install the laravel-mongodb package using the Composer package manager. Open your terminal and execute the following command:

 composer require jenssegers/mongodb

 

Once the package has been successfully installed, we’ll proceed to add the service provider in the app.php configuration file. Let’s add it as shown below:

configapp.php

<?php

 return [



 'providers' => [

         JenssegersMongodbMongodbServiceProvider::class,

 ]

 

 ]

5. Make Base Model:

Create a file named Model.php at the following path: appModels.

Let’s add it as shown below:

appModelsModel.php

<?php

 

namespace AppModels;



use IlluminateDatabaseEloquentFactoriesHasFactory;

use JenssegersMongodbEloquentModel as BaseModel;

 

/**

 * This class represents a base model for MongoDB database connections.

 */

class Model extends BaseModel

{

    /**

     * The MongoDB connection for the model.

     *

     * @var string

     */

    protected $connection = 'mongodb';

}

6. Create a Model and Migration:

Below this command, the generated files would typically be found in their respective directories within your Laravel project:

php artisan make:model Post -m

7. Define the Migration:

Open your posts migration file and add the following code.

<?php

 

use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;

 

class CreatePostsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('posts', function (Blueprint $table) {

            $table->string('title');

            $table->text(content);

            $table->timestamps();

        });

    }

 

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('posts');

    }

}

8. Run Migration:

Open your terminal and execute the following command:

 php artisan migrate

9.Create a Resource Controller:

Open your terminal and execute the following command:

 php artisan make:controller PostController –resource

Open your “routes/web.php” file and include the following route.

 Route::resource(‘posts’, PostController::class);

10.Implement Controller Methods:

In PostController.php, customize the methods to handle CRUD operations for sharks. Here’s an example:

<?php

namespace AppHttpControllers;

use AppHttpControllersController;

use AppModelsPost;

use IlluminateHttpRedirectResponse;

use IlluminateHttpRequest;

use IlluminateViewView;

class PostController extends Controller

{

    /**

     * Display a listing of the resource.

     */

    public function index(): View

    {

        $posts = Post::paginate(10);

        return view('post.index', compact('posts'));

    }

    /**

     * Show the form for creating a new resource.

     */

    public function create(): View

    {

        return view('post.create');

    }

    /**

     * Store a newly created resource in storage.

     */

    public function store(Request $request): RedirectResponse

    {

        $request->validate([

            'title' => 'required',

            'content' => 'required',

        ]);

        Post::create($request->all());

        return redirect()->route('posts.index')

            ->with('success', 'Post created successfully.');

    }

    /**

     * Display the specified resource.

     */

    public function show(Post $post): View

    {

        return view('post.show', compact('post'));

    }

    /**

     * Show the form for editing the specified resource.

     */

    public function edit(Post $post): View

    {

        return view('post.edit', compact('post'));

    }

    /**

     * Update the specified resource in storage.

     */

    public function update(Request $request, Post $post): RedirectResponse

    {

        $request->validate([

            'title' => 'required',

            'content' => 'required',

        ]);

        $post->update($request->all());

        return redirect()->route('posts.index')

            ->with('success', 'Post updated successfully');

    }

    /**

     * Remove the specified resource from storage.

     */

    public function destroy(Post $post): RedirectResponse

    {

        $post->delete();

        return redirect()->route('posts.index')

            ->with('success', 'Product deleted successfully');

    }

}

11.Create Blade Views:

Create Blade views for your resource. Customize these views based on your requirements:

  1. resources/views/post/index.blade.php: Display a list of post.
  2. resources/views/post/create.blade.php: Form to create a new post.
  3. resources/views/post/show.blade.php: Form to edit an existing post.
  4. resources/views/post/edit.blade.php: Form to edit an existing post.

resourcesviewspostlayout.blade.php

<!DOCTYPE html>

<html>

<head>

    <title>Post Crud Operation Using MongoDB</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"

        integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA=="

        crossorigin="anonymous" referrerpolicy="no-referrer" />

</head>

<body>

    <div class="container">

        @yield('content')

    </div>

</body>

</html>

 

resourcesviewspostindex.blade.php


@extends('post.layout')

@section('content')

    <div class="container mt-4">

        <h1 class="mb-4">Post List</h1>

        <div class="d-flex justify-content-between mb-3">

            <a href="{{ route('posts.create') }}" class="btn btn-primary">Add Post</a>

        </div>

        <div class="row">

            <div class="col-12">

                <table class="table table-hover">

                    <thead class="thead-dark">

                        <tr>

                            <th scope="col">SR. NO</th>

                            <th scope="col">Title</th>

                            <th scope="col">Content</th>

                            <th scope="col">Action</th>

                        </tr>

                    </thead>

                    <tbody>

                        @if (count($posts) > 0)

                            @php

                                $i = 0;

                            @endphp

                            @foreach ($posts as $post)

                                <tr>

                                    <th scope="row">{{ ++$i }}</th>

                                    <td>{{ $post->title }}</td>

                                    <td>{{ $post->content }}</td>

                                    <td>

                                        <form action="{{ route('posts.destroy', $post->id) }}" method="POST">

                                            <a class="btn btn-secondary" href="{{ route('posts.show', $post->id) }}" title="Show"><i class="fa-solid fa-eye"></i></a>

                                            <a class="btn btn-secondary"

                                                href="{{ route('posts.edit', $post->id) }}" title="Edit"><i class="fa-solid fa-pencil"></i></a>

                                            @csrf

                                            @method('DELETE')

                                            <button type="submit" class="btn btn-secondary" title="Delete"><i class="fa-solid fa-trash"></i></button>

                                        </form>

                                    </td>

                                </tr>

                            @endforeach

                        @else

                            <tr>

                                <th colspan="4" class="text-center">No data found</th>

                            </tr>

                        @endif

                    </tbody>

                </table>

                <div class="d-flex justify-content-center">

                    {{ $posts->links('vendor.pagination.bootstrap-4') }}

                </div>

            </div>

        </div>

    </div>

@endsection

 

resourcesviewspostcreate.blade.php


@extends('post.layout')

@section('content')

    <div class="row">

        <div class="col-lg-12 margin-tb">

            <div class="pull-left">

                <h2>Create 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">

            <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>Title:</strong>

                    <input type="text" name="title" class="form-control" placeholder="title">

                </div>

            </div>

            <div class="col-xs-12 col-sm-12 col-md-12">

                <div class="form-group">

                    <strong>Content:</strong>

                    <textarea class="form-control" style="height:150px" name="content" placeholder="content"></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

 

resourcesviewspostshow.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>Title:</strong>

                {{ $post->title }}

            </div>

        </div>

        <div class="col-xs-12 col-sm-12 col-md-12">

            <div class="form-group">

                <strong>Content:</strong>

                {{ $post->content }}

            </div>

        </div>

    </div>

@endsection

resourcesviewspostedit.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">

            <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>Title:</strong>

                    <input type="text" name="title" value="{{ $post->title }}" class="form-control"

                        placeholder="Title">

                </div>

            </div>

            <div class="col-xs-12 col-sm-12 col-md-12">

                <div class="form-group">

                    <strong>Content:</strong>

                    <textarea class="form-control" style="height:150px" name="content" placeholder="content">{{ $post->content }}</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

12. Bootstrap Pagination:

Open your terminal and execute the following command:

 php artisan vendor:publish --tag=laravel-pagination

This command will publish the pagination views to your resources/views/vendor/pagination directory. After running the command, you should see a bootstrap-4.blade.php file in that directory. Now, your pagination code should work as expected.

 

13. Run Project:

Open your terminal and execute the following command:

php artisan artisan serve

You can now open the following URL in your web browser:

 

http://localhost:8000/posts

From the same category