Laravel 进行MongoDB CRUD操作
在本章中,我们将学习如何执行CRUD操作。我们将使用Laravel和MongoDB数据库来完成此操作。我们通常使用MongoDB存储数据,因为它占用较少的内存。在今天的市场上,Laravel是一种非常著名的技术。在本示例中,我们将使用Laravel 5.6应用程序执行MongoDB CRUD操作。我们可以使用各个版本的Laravel应用程序,如Laravel 5、6、7和8。在我们的Laravel应用程序中,我们将创建图书、创建、更新、删除和查看。
要创建CRUD(创建,更新,读取和删除),我们将使用composer软件包“jenssegers / laravel-mongodb”。我们可以使用此方法使用模型的eloquent方法,如whereNull,whereIn,collection,orderBy,take,distinct,all,first,whereBetween,get,orWhere skip等。
在我们的下面的示例中,我们将创建名为MongoDB的数据库,并在其中创建“books”集合。之后,我们将使用env文件来配置MongoDB数据库的详细信息。然后,我们将使用Laravel 5.6应用程序来创建CRUD模块。创建CRUD的逐步过程如下所述:
步骤1:
在此步骤中,我们将创建一个MongoDB数据库。在我们的示例中,我们需要创建我们的图书集合和MongoDB数据库。当我们成功安装MongoDB数据库后,我们将使用命令提示符连接到MongoDB。对于连接,我们将创建一个数据库,然后创建集合。之后,我们将使用以下命令插入图书:
mongo
> use hddatabaseep
> db.books.insert( { "name": "laravel", "detail": "test" } )
步骤2:
在这一步中,我们将安装Laravel 5.6项目。为此,我们将使用最新版本的Laravel 5.6应用程序。以下命令将有助于完成此操作。要运行以下命令,我们将使用终端,如下所述:
composer create-project --prefer-dist laravel/laravel blog
步骤3:
在这一步中,我们将进行MongoDB数据库配置。在我们的Laravel 5.6应用程序中,我们将设置数据库的名称、用户名和密码来执行CRUD操作。为此,我们将打开.env文件,然后添加所有细节,如下所述:
.env
MONGO_DB_HOST=127.0.0.1
MONGO_DB_PORT=27017
MONGO_DB_DATABASE=hddatabase
MONGO_DB_USERNAME=
MONGO_DB_PASSWORD=
在此之后,我们将使用database.php配置文件并添加数组的详细信息,如下所述:
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' => []
],
]
]
步骤4:
在这一步中,我们将安装 laravel-mongodb 包。在下面的示例中,我们将使用 Composer 包管理器进行安装。为此,我们将使用命令提示符并运行以下命令:
composer require jenssegers/mongodb
当我们成功安装以上包之后,我们将使用app.php配置文件,以便我们可以添加服务提供者。具体步骤如下:
config/app.php
<?php
return [
....
'providers' => [
....
Jenssegers\Mongodb\MongodbServiceProvider::class,
]
.....
]
步骤5:
在这一步中,我们将创建一个书籍模型。在我们的应用程序中,我们将通过使用Book模型提供与Laravel Eloquent的连接。创建书籍模型的代码如下所示:
app/Book.php
<?php
namespace App;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Book extends Eloquent
{
protected connection = 'mongodb';
protectedcollection = 'books';
/**
* The attributes which are mass assigned will be used.
*
* It will return @var array
*/
protected $fillable = [
'name', 'detail'
];
}
步骤6:
在这一步,我们要添加资源路由。我们将为图书CRUD应用程序添加路由。我们将使用名为”routes/web.php”的文件来添加我们的路由,如下所示:
routes/web.php
Route::resource('books','BookController');
步骤7:
在这一步中,我们将创建BookController。我们将创建BookController作为一个新的控制器。使用这个控制器,我们可以创建资源控制器。创建它的代码如下所示:
php artisan make:controller BookController --resource --model=Book
当我们成功执行此命令时,我们将在“app/Http/Controllers/BookController.php”路径下获得一个新文件。为此,我们将在此控制器中默认创建7个方法,如下所示:
- index()
- edit()
- store()
- destroy()
- create()
- update()
- show()
为此,我们将使用一个名为BookController.php的文件,然后将以下代码放入其中:
app/Http/Controllers/BookController.php
<?php
namespace App\Http\Controllers;
use App\Book;
use Illuminate\Http\Request;
class BookController extends Controller
{
/**
* It is used to show a resource list.
*
* It is used to @return \Illuminate\Http\Response
*/
public function index()
{
books = Book::all();
return view('books.index',compact('books'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* It is used to create a new resource by displaying the form.
*
* It is used to @return \Illuminate\Http\Response
*/
public function create()
{
return view('books.create');
}
/**
* It uses storage to store the above-created resource.
*
* @param \Illuminate\Http\Requestrequest
* It is used to @return \Illuminate\Http\Response
*/
public function store(Request request)
{
request()->validate([
'name' => 'required',
'detail' => 'required',
]);
Book::create(request->all());
return redirect()->route('books.index')
->with('success','Book created successfully.');
}
/**
* The specified resource will be shown by it.
*
* @param \App\Book book
* It is used to @return \Illuminate\Http\Response
*/
public function show(Bookbook)
{
return view('books.show',compact('book'));
}
/**
* It is used to edit the specified resource by displaying the form.
*
* @param \App\Book book
* It is used to @return \Illuminate\Http\Response
*/
public function edit(Bookbook)
{
return view('books.edit',compact('book'));
}
/**
* It uses storage to update the specified resource.
*
* @param \Illuminate\Http\Request request
* @param \App\Bookbook
* It is used to @return \Illuminate\Http\Response
*/
public function update(Request request, Bookbook)
{
request()->validate([
'name' => 'required',
'detail' => 'required',
]);
book->update(request->all());
return redirect()->route('books.index')
->with('success','Book updated successfully');
}
/**
* It uses storage and removes the specified resource from it.
*
* @param \App\Book book
* It is used to @return \Illuminate\Http\Response
*/
public function destroy(Bookbook)
{
$book->delete();
return redirect()->route('books.index')
->with('success','Book deleted successfully');
}
}
步骤8:
在这一步中,我们将创建 Blade 文件。首先,我们将创建布局文件。然后,我们将创建一个新的“books”文件夹。接下来,我们将为我们的 CRUD 操作创建 Blade 文件。我们最终创建的 Blade 文件如下所示:
- blade.php
- blade.php
- blade.php
- blade.php
- blade.php
- blade.php
为此,我们将通过创建以下文件,添加以下代码。
resources/views/books/layout.blade.php
<!DOCTYPE html>
<html>
<head>
<title> MongoDB CRUD Application using Laravel</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">
@yield('content')
</div>
</body>
</html>
resources/views/books/index.blade.php
@extends('books.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Books</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('books.create') }}"> Create New Book</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 (books asbook)
<tr>
<td>{{ ++i }}</td>
<td>{{book->name }}</td>
<td>{{ book->detail }}</td>
<td>
<form action="{{ route('books.destroy',book->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('books.show',book->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('books.edit',book->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
@endsection
resources/views/books/show.blade.php
@extends('books.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2> Show Book</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('books.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>
{{ book->name }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Details:</strong>
{{book->detail }}
</div>
</div>
</div>
@endsection
resources/views/books/create.blade.php
@extends('books.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Add New Book</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('books.index') }}"> Back</a>
</div>
</div>
</div>
@if (errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> Your entered input has some problem. <br><br>
<ul>
@foreach (errors->all() as error)
<li>{{error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('books.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/books/edit.blade.php
@extends('books.layout')
@section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Book</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('books.index') }}"> Back</a>
</div>
</div>
</div>
@if (errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> Your entered input has some problem. <br><br>
<ul>
@foreach (errors->all() as error)
<li>{{error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('books.update',book->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="{{book->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">{{ $book->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
现在我们上面的代码已经准备好运行了。为了快速运行上面的代码,我们将使用以下命令:
php artisan serve
现在我们可以使用浏览器打开以下URL:
http://localhost:8000/books
打开之后,我们可以看到以下输出: