mysql crud

Throughout this tutorial for beginners you’ll learn to use Laravel 5.7 — the latest version of one of the most popular PHP frameworks — to create a CRUD web application with a MySQL database from scratch. We’ll go through the process step by step starting with the installation of Composer (PHP package manager) and continuing on to implementing and serving your application.

在面向初学者的整个教程中,您将学习如何使用Laravel 5.7(一种最受欢迎​​PHP框架之一的最新版本)从零开始创建带有MySQL数据库的CRUD Web应用程序。 我们将从安装Composer(PHP包管理器)开始,逐步进行该过程,然后继续实施和服务您的应用程序。

先决条件 (Prerequisites)

This tutorial assumes you have PHP and MySQL installed on your system. Follow the instructions for your operating system to install both of them.

本教程假定您在系统上安装了PHP和MySQL。 请按照您的操作系统的说明来安装它们。

You also need to be familiar with Linux/macOS bash where we’ll be executing the commands in this tutorial.

您还需要熟悉Linux / macOS bash,我们将在其中执行本教程中的命令。

Familiarly with PHP is required since Laravel is based on PHP.

由于Laravel基于PHP,因此必须熟悉PHP。

For development I will be using an Ubuntu 16.04 machine so the commands in this tutorial are targeting this system, but you should be able to follow this tutorial in any operating system you use.

为了进行开发,我将使用Ubuntu 16.04机器,因此本教程中的命令针对此系统,但是您应该能够在所使用的任何操作系统中遵循本教程。

安装PHP 7.1 (Installing PHP 7.1)

Laravel v5.7 requires PHP 7.1 or above so you need the latest version of PHP installed on your system. The process is straightforward on most systems.

Laravel v5.7需要PHP 7.1或更高版本,因此您需要在系统上安装最新版本PHP。 在大多数系统上,该过程很简单。

On Ubuntu, you can follow these instructions.

在Ubuntu上,您可以按照以下说明进行操作。

First add the ondrej/php PPA which contains the latest version of PHP:

首先添加ondrej/php PPA,其中包含最新版本PHP:

$ sudo add-apt-repository ppa:ondrej/php $ sudo apt-get update

Next, install PHP 7.1 using the following command:

接下来,使用以下命令安装PHP 7.1:

$ sudo apt-get install php7.1

If you are using Ubuntu 18.04, PHP 7.2 is included in the default Ubuntu repository for 18.04 so you should be able to install it using the following command:

如果您使用的是Ubuntu 18.04,则PHP 7.2包含在18.04的默认Ubuntu存储库中,因此您应该能够使用以下命令进行安装:

$ sudo apt-get install php

This tutorial is tested with PHP 7.1 but you can also use more recent versions like PHP 7.2 or PHP 7.3

本教程已经过PHP 7.1的测试,但是您也可以使用更新的版本,例如PHP 7.2或PHP 7.3

安装所需PHP 7.1模块 (Installing the Required PHP 7.1 Modules)

Laravel requires a bunch of modules. You can install them using the following command:

Laravel需要一堆模块。 您可以使用以下命令安装它们:

$ sudo apt-get install php7.1 php7.1-cli php7.1-common php7.1-json php7.1-opcache php7.1-mysql php7.1-mbstring php7.1-mcrypt php7.1-zip php7.1-fpm php7.1-xml

安装PHP Composer (Installing PHP Composer)

Let’s start our journey by installing Composer, the PHP package manager.

让我们通过安装PHP软件包管理器Composer开始我们的旅程。

Navigate in your home directory, then download the installer from the official website using curl:

导航到您的主目录,然后使用curl从官方网站下载安装程序:

$ cd ~ $ curl -sS https://getcomposer.org/installer -o composer-setup.php

You can then install composer globally on your system by using the following command:

然后,可以使用以下命令在系统上全局安装composer

$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

As of this writing, Composer 1.8 will be installed on your system. You can make sure your installation works as expected by running composer in your terminal:

撰写本文时,Composer 1.8将安装在您的系统上。 您可以通过在终端中运行composer来确保安装能够按预期进行:

You should get the following output:

您应该获得以下输出:

______  / ____/___  ____ ___  ____  ____  ________  _____ / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___// /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/                    /_/Composer version 1.8.0 2018-12-03 10:31:16Usage:  command [options] [arguments]Options:  -h, --help                     Display this help message  -q, --quiet                    Do not output any message  -V, --version                  Display this application version      --ansi                     Force ANSI output      --no-ansi                  Disable ANSI output  -n, --no-interaction           Do not ask any interactive question      --profile                  Display timing and memory usage information      --no-plugins               Whether to disable plugins.  -d, --working-dir=WORKING-DIR  If specified, use the given directory as working directory.  -v|vv|vvv, --verbose           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

For more information check out this tutorial.

有关更多信息,请查看本教程 。

If you’ve successfully installed Composer in your system, you are ready to create a Laravel 5.7 project.

如果已在系统中成功安装Composer,则准备创建Laravel 5.7项目。

安装和创建Laravel 5.7项目 (Installing and Creating a Laravel 5.7 Project)

In this section we’ll introduce Laravel and then proceed it to install and create a Laravel 5.7 project.

在本节中,我们将介绍Laravel,然后继续进行安装和创建Laravel 5.7项目。

关于Laravel (About Laravel)

Laravel docs describe it as:

Laravel文档将其描述为:

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:

Laravel是一个具有表达力,优雅语法的Web应用程序框架。 我们认为,发展必须是一种令人愉悦的创造力,才能真正实现。 Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发工作的痛苦,例如:

Laravel is accessible, yet powerful, providing tools needed for large, robust applications.

Laravel易于访问,但功能强大,可提供大型,强大的应用程序所需的工具。

Generating a Laravel 5.7 project is easy and straightforward. In your terminal, run the following command:

生成Laravel 5.7项目既简单又直接。 在您的终端中,运行以下命令:

$ composer create-project --prefer-dist laravel/laravel laravel-first-crud-app

This will install laravel/laravel v5.7.19.

这将安装laravel/laravel v5.7.19

Note: Make sure you have at least PHP 7.1 installed on your system. Otherwise, composer will use Laravel 5.5 for your project.

注意 :确保您的系统上至少安装了PHP 7.1。 否则,作曲家将在您的项目中使用Laravel 5.5。

You can verify the installed version in your project using:

您可以使用以下方法在项目中验证安装的版本:

$ cd laravel-first-crud-app $ php artisan -V Laravel Framework 5.7.22

安装前端依赖项 (Installing the Front-End Dependencies)

In your generated project, you can see that a package.json file is generated which includes many front-end libraries that can be used by your project:

在生成的项目中,您可以看到生成了一个package.json文件,其中包含许多可供项目使用的前端库:

  • axios,轴距
  • bootstrap,引导程序
  • cross-env,交叉环境
  • jquery,jQuery,
  • laravel-mix,laravel-mix,
  • lodash,Lodash,
  • popper.js,popper.js,
  • resolve-url-loader,resolve-url-loader,
  • sass,ass
  • sass-loader,萨斯装载机
  • vue.Vue。

Note: You can use your preferred libraries with Laravel not specifically the ones added to package.json.

注意 :您可以将首选的库与Laravel结合使用,而不必专门添加到package.json

The package.json file in your Laravel project includes a few packages such as vue and axios to help you get started building your JavaScript application.

Laravel项目中的package.json文件包括一些软件包,例如vueaxios ,可帮助您开始构建JavaScript应用程序。

It also includes bootstrap to help you get started with Bootstrap for styling your UI.

它还包括bootstrap以帮助您开始使用Bootstrap来设计UI样式。

It includes Laravel Mix to help you compile your SASS files to plain CSS.

它包括Laravel Mix ,可帮助您将SASS文件编译为纯CSS。

You need to use npm to install the front-end dependencies:

您需要使用npm来安装前端依赖项:

$ npm install

After running this command a node_modules folder will be created and the dependencies will be installed into it.

运行此命令后,将创建一个node_modules文件夹并将依赖项安装到其中。

Note: You need to have Node.js and npm installed on your system before you can install the front-end dependencies.

注意 :必须先在系统上安装Node.js和npm,然后才能安装前端依赖项。

创建一个MySQL数据库 (Creating a MySQL Database)

Let’s now create a MySQL database that we’ll use to persist data in our Laravel application. In your terminal, run the following command to run the mysql client:

现在,让我们创建一个MySQL数据库,该数据库将用于将数据持久保存在Laravel应用程序中。 在您的终端中,运行以下命令以运行mysql客户端:

$ mysql -u root -p

When prompted, enter the password for your MySQL server when you’ve installed it.

出现提示时,请在安装MySQL服务器后输入密码。

Next, run the following SQL statement to create a db database:

接下来,运行以下SQL语句创建一个db数据库:

mysql> create database db;

Open the .env file and update the credentials to access your MySQL database:

打开.env文件并更新凭据以访问您MySQL数据库:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db DB_USERNAME=root DB_PASSWORD=******

You need to enter the database name, the username and password.

您需要输入数据库名称,用户名和密码。

At this point, you can run the migrate command to create your database and a bunch of SQL tables needed by Laravel:

在这一点上,你可以运行migrate命令来创建数据库和一帮由Laravel需要SQL表:

Note: You can run the migrate command at any other points of your development to add other SQL tables in your database or to later your database if you need to add any changes later.

注意 :您可以在开发的任何其他点运行migrate命令,以在数据库中添加其他SQL表,或者如果以后需要添加任何更改,则可以在以后的数据库中运行。

创建您的第一个Laravel模型 (Creating your First Laravel Model)

Laravel uses the MVC architectural pattern to organize your application in three decoupled parts:

Laravel使用MVC架构模式将您的应用程序分为三个分离的部分:

  • The Model which encapsulates the data access layer,封装数据访问层的模型,
  • The View which encapsulates the representation layer,封装表示层的View,
  • Controller which encapsulates the code to control the application and communicates with the model and view layers.封装代码以控制应用程序并与模型和视图层通信的控制器。

Wikipedia defines MVC as:

维基百科将MVC定义为:

Model–view–controller is an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.

模型-视图-控制器 是一种通常用于开发用户界面的体系结构模式 ,它将应用程序分为三个相互联系的部分。 这样做是为了将信息的内部表示形式与信息呈现给用户和从用户接受的方式分开。

Now, let’s create our first Laravel Model. In your terminal, run the following command:

现在,让我们创建第一个Laravel模型。 在您的终端中,运行以下命令:

$ php artisan make:model Contact --migration

This will create a Contact model and a migration file. In the terminal, we get an output similar to:

这将创建一个联系人模型和一个迁移文件。 在终端中,我们得到类似于以下内容的输出:

Model created successfully. Created Migration: 2019_01_27_193840_create_contacts_table

Open the database/migrations/xxxxxx_create_contacts_table migration file and update it accordingly:

打开database/migrations/xxxxxx_create_contacts_table迁移文件并相应地更新它:

<?phpuse Illuminate\Support\Facades\Schema;use Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class CreateContactsTable extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('contacts', function (Blueprint $table) {            $table->increments('id');            $table->timestamps();            $table->string('first_name');            $table->string('last_name');            $table->string('email');            $table->string('job_title');            $table->string('city');               $table->string('country');                    });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists('contacts');    }}

We added the first_name, last_name, email, job_title, city and country fields in the contacts table.

我们在contacts表中添加了first_namelast_nameemailjob_titlecitycountry字段。

You can now create the contacts table in the database using the following command:

现在,您可以使用以下命令在数据库中创建contacts表:

$ php artisan migrate

Now, let’s look at our Contact model, which will be used to interact with the contacts database table. Open the app/Contact.php and update it:

现在,让我们看一下Contact模型,该模型将用于与contacts数据库表进行交互。 打开app/Contact.php并更新它:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Contact extends Model{    protected $fillable = [        'first_name',        'last_name',        'email',        'city',        'country',        'job_title'           ];}

创建控制器和路由 (Creating the Controller and Routes)

After creating the model and migrating our database, let’s now create the controller and the routes for working with the Contact model. In your terminal, run the following command:

创建模型并迁移我们的数据库之后,现在让我们创建用于处理Contact模型的控制器和路由。 在您的终端中,运行以下命令:

$ php artisan make:controller ContactController --resource

Laravel resource routing assigns the typical “CRUD” routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for “photos” stored by your application. Using the make:controller Artisan command, we can quickly create such a controller.

Laravel资源路由通过单行代码将典型的“ CRUD”路由分配给控制器。 例如,您可能希望创建一个控制器来处理应用程序存储的所有HTTP对“照片”的HTTP请求。 使用make:controller Artisan命令,我们可以快速创建这样的控制器。

This command will generate a controller at app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations.

此命令将在app/Http/Controllers/PhotoController.php生成一个控制器。 控制器将包含每个可用资源操作的方法。

Open the app/Http/Controllers/ContactController.php file. This is the initial content:

打开app/Http/Controllers/ContactController.php文件。 这是初始内容:

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class ContactController extends Controller{    /**     * Display a listing of the resource.     *     * @return \Illuminate\Http\Response     */    public function index()    {        //    }    /**     * Show the form for creating a new resource.     *     * @return \Illuminate\Http\Response     */    public function create()    {        //    }    /**     * Store a newly created resource in storage.     *     * @param  \Illuminate\Http\Request  $request     * @return \Illuminate\Http\Response     */    public function store(Request $request)    {        //    }    /**     * Display the specified resource.     *     * @param  int  $id     * @return \Illuminate\Http\Response     */    public function show($id)    {        //    }    /**     * Show the form for editing the specified resource.     *     * @param  int  $id     * @return \Illuminate\Http\Response     */    public function edit($id)    {        //    }    /**     * Update the specified resource in storage.     *     * @param  \Illuminate\Http\Request  $request     * @param  int  $id     * @return \Illuminate\Http\Response     */    public function update(Request $request, $id)    {        //    }    /**     * Remove the specified resource from storage.     *     * @param  int  $id     * @return \Illuminate\Http\Response     */    public function destroy($id)    {        //    }}

The ContactController class extends Controller class available from Laravel and defines a bunch of methods which will be used to do the CRUD operations against the Contact model.

ContactController类扩展了Laravel提供的Controller类,并定义了一堆方法,这些方法将用于对Contact模型进行CRUD操作。

You can read the role of the method on the comment above it.

您可以在该方法上方的注释上阅读该方法的作用。

Now we need to provide implementations for these methods.

现在,我们需要提供这些方法的实现。

But before that, let’s add routing. Open the routes/web.php file and update it accordingly:

但在此之前,让我们添加路由。 打开routes/web.php文件并相应地更新它:

<?phpRoute::get('/', function () {    return view('welcome');});Route::resource('contacts', 'ContactController');

Using the resource() static method of Route, you can create multiple routes to expose multiple actions on the resource.

使用Routeresource()静态方法,可以创建多个路由以公开对资源的多个操作。

These routes are mapped to various ContactController methods which we will need to implement in the next section:

这些路由映射到各种ContactController方法,我们将在下一部分中实现这些方法:

  • GET/contacts, mapped to the index() method,

    GET /contacts ,映射到index()方法,

  • GET /contacts/create, mapped to the create() method,

    GET /contacts/create ,映射到create()方法,

  • POST /contacts, mapped to the store() method,

    POST /contacts ,映射到store()方法,

  • GET /contacts/{contact}, mapped to the show() method,

    GET /contacts/{contact} ,映射到show()方法,

  • GET /contacts/{contact}/edit, mapped to the edit() method,

    GET /contacts/{contact}/edit ,映射到edit()方法,

  • PUT/PATCH /contacts/{contact}, mapped to the update() method,

    PUT / PATCH /contacts/{contact} ,映射到update()方法,

  • DELETE /contacts/{contact}, mapped to the destroy() method.

    DELETE /contacts/{contact} ,映射到destroy()方法。

These routes are used to serve HTML templates and also as API endpoints for working with the Contact model.

这些路由用于服务HTML模板,也用作与Contact模型一起使用的API端点。

Note: If you want to create a controller that will only expose a RESTful API, you can use the apiResource method to exclude the routes that are used to serve the HTML templates:

注意 :如果要创建仅公开RESTful API的控制器,则可以使用apiResource方法排除用于提供HTML模板的路由:

Route::apiResource('contacts', 'ContactController');

实施CRUD操作 (Implementing the CRUD Operations)

Let’s now implement the controller methods alongside the views.

现在,让我们在视图旁边实现控制器方法。

C:实施创建操作并添加表单 (C: Implementing the Create Operation and Adding a Form)

The ContactController includes

ContactController包括

  • the store() method that maps to the POST /contacts API endpoint which will be used to create a contact in the database, and

    映射到POST /contacts API端点的store()方法,该端点将用于在数据库中创建联系人,并且

  • the create() that maps to the GET /contacts/create route which will be used to serve the HTML form used to submit the contact to POST /contacts API endpoint.

    映射到GET /contacts/create路由的create() ,该路由将用于提供HTML表单,该表单用于将联系人提交到POST /contacts API端点。

Let’s implement these two methods.

让我们实现这两种方法。

Re-open the app/Http/Controllers/ContactController.php file and start by importing the Contact model:

重新打开app/Http/Controllers/ContactController.php文件,并从导入Contact模型开始:

use App\Contact;

Next, locate the store() method and update it accordingly:

接下来,找到store()方法并相应地更新它:

public function store(Request $request)    {        $request->validate([            'first_name'=>'required',            'last_name'=>'required',            'email'=>'required'        ]);        $contact = new Contact([            'first_name' => $request->get('first_name'),            'last_name' => $request->get('last_name'),            'email' => $request->get('email'),            'job_title' => $request->get('job_title'),            'city' => $request->get('city'),            'country' => $request->get('country')        ]);        $contact->save();        return redirect('/contacts')->with('success', 'Contact saved!');    }

Next, locate the create() method and update it:

接下来,找到create()方法并对其进行更新:

public function create() { return view('contacts.create'); }

The create() function makes use of the view() method to return the create.blade.php template which needs to be present in the resources/views folder.

create()函数利用view()方法返回create.blade.php模板,该模板需要出现在resources/views文件夹中。

Before creating the create.blade.php template we need to create a base template that will be extended by the create template and all the other templates that will create later in this tutorial.

在创建create.blade.php模板之前,我们需要创建一个基础模板,该模板将由create模板以及将在本教程后面部分创建的所有其他模板进行扩展。

In the resources/views folder, create a base.blade.php file:

resources/views文件夹中,创建一个base.blade.php文件:

$ cd resources/views $ touch base.blade.php

Open the resources/views/base.blade.php file and add the following blade template:

打开resources/views/base.blade.php文件并添加以下刀片服务器模板:

<!DOCTYPE html><html lang="en"><head>  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <title>Laravel 5.7 & MySQL CRUD Tutorial</title>  <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" /></head><body>  <div class="container">    @yield('main')  </div>  <script src="{{ asset('js/app.js') }}" type="text/js"></script></body></html>

Now, let’s create the create.blade.php template. First, create a contacts folder in the views folder:

现在,让我们创建create.blade.php模板。 首先,在views文件夹中创建一个contact文件夹:

$ mkdir contacts

Next, create the template

接下来,创建模板

$ cd contacts $ touch create.blade.php

Open the resources/views/contacts/create.blade.php file and add the following code:

打开resources/views/contacts/create.blade.php文件并添加以下代码:

@extends('base')@section('main')<div class="row"> <div class="col-sm-8 offset-sm-2">    <h1 class="display-3">Add a contact</h1>  <div>    @if ($errors->any())      <div class="alert alert-danger">        <ul>            @foreach ($errors->all() as $error)              <li>{{ $error }}</li>            @endforeach        </ul>      </div><br />    @endif      <form method="post" action="{{ route('contacts.store') }}">          @csrf          <div class="form-group">                  <label for="first_name">First Name:</label>              <input type="text" class="form-control" name="first_name"/>          </div>          <div class="form-group">              <label for="last_name">Last Name:</label>              <input type="text" class="form-control" name="last_name"/>          </div>          <div class="form-group">              <label for="email">Email:</label>              <input type="text" class="form-control" name="email"/>          </div>          <div class="form-group">              <label for="city">City:</label>              <input type="text" class="form-control" name="city"/>          </div>          <div class="form-group">              <label for="country">Country:</label>              <input type="text" class="form-control" name="country"/>          </div>          <div class="form-group">              <label for="job_title">Job Title:</label&gt;              <input type="text" class="form-control" name="job_title"/>          </div>                                   <button type="submit" class="btn btn-primary-outline">Add contact</button>      </form>  </div></div></div>@endsection

This is a screenshot of our create form!

这是我们创建表单的屏幕截图!

Fill out the form and click on the Add contact button to create a contact in the database. You should be redirected to /contacts route which doesn’t have a view associated to it yet.

填写表格,然后单击“ 添加联系人”按钮以在数据库中创建联系人。 您应该重定向到尚未关联视图的/ contacts路由。

R:实现读取操作并获取数据 (R: Implementing the Read Operation and Getting Data)

Next, let’s implement the read operation to get and display contacts data from our MySQL database.

接下来,让我们实现读取操作,以从MySQL数据库获取和显示联系人数据。

Go to the app/Http/Controllers/ContactController.php file, locate the index() method and update it:

转到app/Http/Controllers/ContactController.php文件,找到index()方法并对其进行更新:

public function index()    {        $contacts = Contact::all();        return view('contacts.index', compact('contacts'));    }

Next, you need to create the index template. Create a resources/views/contacts/index.blade.php file:

接下来,您需要创建索引模板。 创建一个resources/views/contacts/index.blade.php文件:

$ touch index.blade.php

Open the resources/views/contacts/index.blade.php file and add the following code:

打开resources/views/contacts/index.blade.php文件并添加以下代码:

@extends('base')@section('main')<div class="row"><div class="col-sm-12">    <h1 class="display-3">Contacts</h1>      <table class="table table-striped">    <thead>        <tr>          <td>ID</td>          <td>Name</td>          <td>Email</td>          <td>Job Title</td>          <td>City</td>          <td>Country</td>          <td colspan = 2>Actions</td>        </tr>    </thead>    <tbody>        @foreach($contacts as $contact)        <tr>            <td>{{$contact->id}}</td>            <td>{{$contact->first_name}} {{$contact->last_name}}</td>            <td>{{$contact->email}}</td>            <td>{{$contact->job_title}}</td>            <td>{{$contact->city}}</td>            <td>{{$contact->country}}</td>            <td>                <a href="{{ route('contacts.edit',$contact->id)}}" class="btn btn-primary">Edit</a>            </td>            <td>                <form action="{{ route('contacts.destroy', $contact->id)}}" method="post">                  @csrf                  @method('DELETE')                  <button class="btn btn-danger" type="submit">Delete</button>                </form>            </td>        </tr>        @endforeach    </tbody>  </table><div></div>@endsection

U:实施更新操作 (U: Implementing the Update Operation)

Next, we need to implement the update operation. Go to the app/Http/Controllers/ContactController.php file, locate the edit($id) method and update it:

接下来,我们需要执行更新操作。 转到app/Http/Controllers/ContactController.php文件,找到edit($id)方法并对其进行更新:

public function edit($id)    {        $contact = Contact::find($id);        return view('contacts.edit', compact('contact'));            }

Next, you need to implement the update() method:

接下来,您需要实现update()方法:

public function update(Request $request, $id)    {        $request->validate([            'first_name'=>'required',            'last_name'=>'required',            'email'=>'required'        ]);        $contact = Contact::find($id);        $contact->first_name =  $request->get('first_name');        $contact->last_name = $request->get('last_name');        $contact->email = $request->get('email');        $contact->job_title = $request->get('job_title');        $contact->city = $request->get('city');        $contact->country = $request->get('country');        $contact->save();        return redirect('/contacts')->with('success', 'Contact updated!');    }

Now, you need to add the edit template. Inside the resources/views/contacts/, create an edit.blade.php file:

现在,您需要添加编辑模板。 在resources/views/contacts/ ,创建一个edit.blade.php文件:

$ touch edit.blade.php

Open the resources/views/contacts/edit.blade.php file and add this code:

打开resources/views/contacts/edit.blade.php文件并添加以下代码:

@extends('base') @section('main')<div class="row">    <div class="col-sm-8 offset-sm-2">        <h1 class="display-3">Update a contact</h1>        @if ($errors->any())        <div class="alert alert-danger">            <ul>                @foreach ($errors->all() as $error)                <li>{{ $error }}</li>                @endforeach            </ul>        </div>        <br />         @endif        <form method="post" action="{{ route('contacts.update', $contact->id) }}">            @method('PATCH')             @csrf            <div class="form-group">                <label for="first_name">First Name:</label>                <input type="text" class="form-control" name="first_name" value={{ $contact->first_name }} />            </div>            <div class="form-group">                <label for="last_name">Last Name:</label>                <input type="text" class="form-control" name="last_name" value={{ $contact->last_name }} />            </div>            <div class="form-group">                <label for="email">Email:</label>                <input type="text" class="form-control" name="email" value={{ $contact->email }} />            </div>            <div class="form-group">                <label for="city">City:</label>                <input type="text" class="form-control" name="city" value={{ $contact->city }} />            </div>            <div class="form-group">                <label for="country">Country:</label>                <input type="text" class="form-control" name="country" value={{ $contact->country }} />            </div>            <div class="form-group">                <label for="job_title">Job Title:</label>                <input type="text" class="form-control" name="job_title" value={{ $contact->job_title }} />            </div>            <button type="submit" class="btn btn-primary">Update</button>        </form>    </div></div>@endsection

D:实施删除操作 (D: Implementing the Delete Operation)

Finally, we’ll proceed to implement the delete operation. Go to the app/Http/Controllers/ContactController.php file, locate the destroy() method and update it accordingly:

最后,我们将继续执行删除操作。 转到app/Http/Controllers/ContactController.php文件,找到destroy()方法并相应地更新它:

public function destroy($id)    {        $contact = Contact::find($id);        $contact->delete();        return redirect('/contacts')->with('success', 'Contact deleted!');    }

You can notice that when we redirect to the /contacts route in our CRUD API methods, we also pass a success message but it doesn't appear in our index template. Let's change that!

您会注意到,当我们在CRUD API方法中重定向到/contacts路由时,我们还会传递一条成功消息,但它不会出现在index模板中。 让我们改变它!

Go to the resources/views/contacts/index.blade.php file and add the following code:

转到resources/views/contacts/index.blade.php文件并添加以下代码:

<div class="col-sm-12">  @if(session()->get('success'))    <div class="alert alert-success">      {{ session()->get('success') }}      </div>  @endif</div>

We also need to add a button to takes us to the create form. Add this code below the header:

我们还需要添加一个按钮以将我们带到创建表单。 将此代码添加到标题下面:

<div>    <a style="margin: 19px;" href="{{ route('contacts.create')}}" class="btn btn-primary">New contact</a></div>

This is a screenshot of the page after we created a contact:

这是我们创建联系人后的页面截图:

结论 (Conclusion)

We’ve reached the end of this tutorial. We created a CRUD application with Laravel 5.7, PHP 7.1 and MySQL.

我们已经到了本教程的结尾。 我们使用Laravel 5.7,PHP 7.1和M​​ySQL创建了一个CRUD应用程序。

Hope you enjoyed the tutorial and see you in the next one!

希望您喜欢本教程,并在下一个教程中再见!

翻译自: https://www.freecodecamp.org/news/laravel-5-7-tutorial-build-your-first-crud-app-with-laravel-and-mysql-15cbd06c6cef/

mysql crud

mysql crud_如何使用Laravel和MySQL构建您的第一个CRUD应用相关推荐

  1. MySQL 数据库之 MMM 高可用架构构建

    文章目录 一.MMM 概述 1. 什么是 MMM 2. 应用场景 3. MMM 特点 4. 关于 MMM 高可用架构的说明 5. 用户及授权 二.案例环境 1. 服务器配置 2. 服务器环境 3. 修 ...

  2. mysql主从同步加密_教你构建MySQL主从结构,实现基于SSL加密的主从同步机制

    实验环境RHEL6.4 admin1.tuchao.com    192.168.1.201    主服务器 admin2.tuchao.com    192.168.1.202    从服务器 先在 ...

  3. larvel 中的api.php_Laravel API 系列教程(一): 基于 Laravel 5.5 构建 测试 RESTful API...

    Laravel API 系列教程(一): 基于 Laravel 5.5 构建 & 测试 RESTful API 由 学院君 创建于2年前, 最后更新于 9个月前 版本号 #3 171702 v ...

  4. 零点起飞学mysql视频_零点起飞学MySQL

    第1篇 MySQL基础 第1章 数据库的安装(教学视频:25分钟) 2 1.1 MySQL概述 2 1.1.1 MySQL特性以及历史 2 1.1.2 MySQL的获取 3 1.2 MySQL的安装 ...

  5. MySQL学习笔记之九:MySQL Replication

    Mysql内建的复制功能是构建大型.高性能应用程序的基础.复制功能不仅有利于构建高性能的应用,同时也是高可用性.可扩展性.灾难恢复.备份以及数据仓库等工作的基础. 一.复制概述 1.复制的功用 数据分 ...

  6. php mysql切换版本5.7_phpstudy 升级 MySQL版本到MySQL5.7

    #### 起因:我用laravel6做迁移的时候,总是报这个错误 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified k ...

  7. mysql 硬负载_为啥单机MySQL又遭遇瓶颈?MySQL主从复制替你解决单机问题

    成长是一棵树,总是在你不知不觉的情况下快乐长大:成长是一株草,总是在你不知不觉的情况下长满大地:成长是一朵花,总是在你不知不觉的情况下开满山头. 这不,随着时间的迁移.项目网站的用户量.数据量持续上升 ...

  8. mysql 迁移到tidb_通过从MySQL迁移到TiDB来水平扩展Hive Metastore数据库

    mysql 迁移到tidb Industry: Knowledge Sharing 行业:知识共享 Author: Mengyu Hu (Platform Engineer at Zhihu) 作者: ...

  9. docker mysql主从_使用docker 实现MySQL主从同步/读写分离

    1. 利用 docker 实现 mysql 主从同步 / 读写分离 为了保证数据的完整和安全,mysql 设计了主从同步,一个挂掉还可以用另个.最近重构论坛,想来改成主从吧.担心失误,就先拿 dock ...

最新文章

  1. 在springboot项目中如何创建子项目
  2. 从Gradle自动将工件提升到Maven Central
  3. Jzoj4743 积木
  4. springboot初始篇(一)
  5. 【2】SCN-Ribbon负载均衡
  6. RTT——IO设备管理篇·基本概念理解
  7. stm32之I2C编程前期准备
  8. html制作古诗念奴娇,《念奴娇·赤壁怀古》_苏轼的诗词_诗词名句网
  9. 读《富爸爸,穷爸爸》后感(二)
  10. MacBook Pro 屏幕黑线、条纹、线条、舞台灯、残影、横线这样的排线门问题你遇到了吗?很有可能源于官方的设计缺陷,你该何去何从?
  11. [IOI2018]-day1 简要题解
  12. ionic刷新html页面,Ionic实现页面下拉刷新(ion-refresher)功能代码
  13. 移动硬盘插服务器上坏了,移动硬盘接口坏了怎么办解决教程
  14. PHP网页的工作原理
  15. flutter 九宫格菜单_flutter九宫格图片查看器
  16. java web 开发是做什么用的?
  17. (二十七)论文阅读 | 目标检测之MAL
  18. 邮箱/手机号等敏感信息掩码
  19. php 对接 新酷卡,新酷卡socket对接支持读取信息发送/接收短信及参数命令
  20. c语言中的头文件stdlib.h的作用,C语言头文件#includestdlib.h的作用

热门文章

  1. 结业考试笔记 2014中超联赛项目笔记 0327
  2. 03 掌握C#控制台程序的结构组成 1214
  3. 办公自动化-使用python-docx生成文档-0223
  4. 数据结构与算法-二叉树的名词概念与相关数据的计算
  5. 除了默认的docker0网桥,启动Docker服务怎么指定使用的网桥
  6. PHP学习笔记【9】_表达式
  7. 2004-11-3 + 扩展Forms验证
  8. Serverless 实战 —— 轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
  9. Vue Router的详细教程
  10. 容器编排技术 -- Kubernetes kubectl create service nodeport 命令详解