Laravel-MongoDB CRUD

Create Views

Now we need to create the views referenced in the controller. Views are named <viewname>.blade.php and the location is resources/views/

So the views referenced in the BookController are

bookindex.blade.php	BookController@index
bookview.blade.php	BookController@show
bookadd.blade.php	BookController@create 
bookedit.blade.php	BookController@edit

The update, store and delete methods all return the bookindex view.

The css for your views go in public/css. This may be included in your views as below:

<link href="/css/lib.css" rel="stylesheet">

A sample view file bookindex.blade.php is given below:

<!DOCTYPE html>
        <title>Book Index</title>
        <link href="/css/lib.css" rel="stylesheet">
        <h1>Welcome to Library</h1>
        <h2>Index of Books</h2>
            <th>Book Title</th>
            @foreach ($books as $i => $book)
             <td>{{ $i+1 }}</td>
	     <td>{{ $book{'title'} }}</td>
	     <td>{{ isset( $book{'isbn'} ) ?  $book{'isbn'} : ' - ' }}</td>
	     <td>{{ $book{'author'} }}</td>
	     <td>{{ $book{'category'} }}</td>
             <form action="/books/{{ $book{'_id'} }}" method="POST">
  {{ csrf_field() }}
  <input type="button" class="book-action" value="View" onclick="window.location ='{{ route('', ['book' => $book{'_id'}]) }}'">  
  <input type="button" class="book-action" value="Edit" onclick="window.location ='{{ route('books.edit', ['book' => $book{'_id'}]) }}'">  
   <input type="hidden" class="book-action" name="_method" value="DELETE"/>
   <input type="submit" class="book-action" name="del" value="Delete"/>

        <input type="button" class="book-action big" value="Add a Book" onclick="window.location ='{{ route('books.create') }}'">

Notice that instead of giving URL directly for redirecting, we are using the route names. Also we are using Laravel's form spoofing. The form with POST method has a hidden input with name "_method" and value "DELETE". This tells Laravel to invoke DELETE method when the submit button is pressed. The view and edit buttons redirect to the corresponding routes.

The complete code for all views as well as the full code for model and controller can be found in our Github.

Once you have your model, controller and views set-up, you may go to /books to find the index of all books. The index has buttons for view, edit, delete and add book which points to the corresponding routes.


When you invoke store method you may get the following error
post method fails
TokenMismatchException in VerifyCsrfToken.php line 67:

To remove this error, add the following line inside your forms:

	{{ csrf_field() }}

This will generate a verification token for the middleware.

Post a comment


Your Comment

Email (We dont publish it)


binu | October 10, 2016 11:25 PM |

Is there any other way other than form spoofing to invoke delete?