Laravel with MongoDB CURD operations - part 2

We will create simple page with posts.

This is our post structure.

PostController
Post model
inside views/posts folder
    index.blade
    add.blade
    edit.blade

Create controller using following command.

php artisan make:controller PostController -- resource

Then you can get PostController in your controller folder with method for show,add,edit, delete and update.Open that controller we are going to add some data to mongodb collection.

Inside your PostController fill the create method by returning the add view.
Your method now looks like this.

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



Now you need to add route for view add add page.
Go to routes/web.php file and add the following route.

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

We added all the resource routes at once.Now we have routes for show all posts, add post, show post by id, edit post and delete post.You can see your route list by typing following command in your console.

php artisan route:list

Then you can see the following routes are there.

 GET|HEAD  | posts                  | posts.index   | App\Http\Controllers\PostController@index                              | web          |
|        | POST      | posts                  | posts.store   | App\Http\Controllers\PostController@store                              | web          |
|        | GET|HEAD  | posts/create           | posts.create  | App\Http\Controllers\PostController@create                             | web          |
|        | DELETE    | posts/{post}           | posts.destroy | App\Http\Controllers\PostController@destroy                            | web          |
|        | PUT|PATCH | posts/{post}           | posts.update  | App\Http\Controllers\PostController@update                             | web          |
|        | GET|HEAD  | posts/{post}           | posts.show    | App\Http\Controllers\PostController@show                               | web          |

|        | GET|HEAD  | posts/{post}/edit      | posts.edit    | App\Http\Controllers\PostController@edit                               | web 



We are using posts/create route for display the "add post" form.
Now you run {YOUR_BASE_URL}/posts/create it returns error.
In your case it might be localhost:8000/posts/create

We will add view to avoid the error.
In your views forder create a folder called "posts" and create a file add.blade.php inside the posts folder.

Add the following html file in your add.blade.php file

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/style.css"></link>
</head>
<body>

<h3>Add post</h3>

<div class="container">
  <form action="#">
    {{ csrf_field() }}
    <label for="title">Title</label>
    <input type="text" name="title" placeholder="Title">

    <label for="desc">Description</label>
    <textarea name="desc" placeholder="Post Description" style="height:200px"></textarea>

    <input type="submit" value="Submit">
  </form>
</div>

</body>
</html>

I have added style.css file inside the public/css folder and add following styles.

body {font-family: Arial, Helvetica, sans-serif;}

input[type=text], select, textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    margin-top: 6px;
    margin-bottom: 16px;
    resize: vertical;
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    padding: 12px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

input[type=submit]:hover {
    background-color: #45a049;
}

.container {
    border-radius: 5px;
    background-color: #f2f2f2;
    padding: 20px;
    margin: 40px;

}


Now your form look like this.



Now wee need to pass the data to controller. We will use store() method for that.
In your route list you can see POST /post route is for store() method.In your html file change the form action to "posts" and method to POST.Now it looks this.

<form action="/posts" method="POST">

Now will check values in store method.
Add following lines to your store() method.

      var_dump($request->all());
   die();

If you can see the values when you submit the form you are done until this point.

Now only we need to save data to mongodb collection and redirect to the back.
For that we need a model.
Run the following command to make the Post model.

php artisan make:model Post

Now you have Post model in your app directory and open it.
Change the line 
use Jenssegers\Mongodb\Eloquent\Model to 
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

Add the following line.
use Jenssegers\Mongodb\Eloquent\HybridRelations;

Change the class Post extends Model to class Post extends Eloquent

Add use statement, database connection and collection name t the model.

    use HybridRelations;

  protected $connection = 'mongodb';

  protected $collection = 'post';

Here I have used HybridRelations for use both mySQL and mongdb.
If you are using only mongodb without HybridRelation you can do it.

We are going to use post collection to add posts.We don't need to create a collection on mongodb before start like mySQL.

Now we are going to write the method to save data to mongodb post collection.
Open your PostController and fill the store method.It should be look like following.

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $post = new Post();

      $post->title = $request->title;
      $post->description = $request->desc;

      $post->save();
    }

Now you have successfully implement the save post to mongodb implementation !

Check your code is working. Add some data to Post form and click submit. Check you mongodb database using following command.

db.post.find();

Go to your shell that you have install the mongo.Start the server.Open a new shell and type the following command to connect.

> mongo

Go to your database by typing following command.You have to give the same name as you give in your .env file database name.

> use yourdatabasename  

You can see your data has been saved as json format.

> db.post.find();                                                                                            
{ "_id" : ObjectId("5b1e446816cd2c1ccc0075c2"), "title" : "Test post", "description" : new post, "updated_at" : ISODate("2018-06-11T09:44:08Z"), "created_at" : ISODate("2018-06-11T09:44:08Z") } 

Finally we add return redirect()->back(); line to store() method to redirect the user to back.

Now your store() method looks like this.

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $post = new Post();

      $post->title = $request->title;
      $post->description = $request->desc;

      $post->save();
    }

Now all done ! Enjoy saving data to mongodb and next we will discuss how to display data from the database.





Comments

Popular posts from this blog

Laravel with MongoDB CURD operations - part 1

Laravel with MongoDB CURD operations - part 3