Laravel 5.8简明教程
在这个面向初学者的教程中,我们将学习如何使用最新的PHP开发框架 Laravel 5.8,来创建一个基于MySQL数据库的Web应用,实现联系人的 增删改查功能。
1、安装PHP环境
Laravel 5.8 要求PHP 7.1+,mysql>5.7.7,因此我们需要先安装最新版的PHP。在大多数 系统上这个过程都很简单。
1.1 安装PHP7.1
在ubuntu上执行以下命令:
1 2 3 |
~$ sudo add-apt-repository ppa:ondrej/php ~$ sudo apt-get update ~$ sudo apt-get install php7.1 |
如果你的ubuntu版本是18.04,那么默认的软件仓里就包含了PHP7.2,因此可以 直接安装:
1 |
~$ sudo apt-get install php |
1.2 安装必要的PHP模块
Laravel 5.8需要一些扩展模块,可以使用下面的命令安装:
1 |
~ $ 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 |
1.3 安装PHP Composer
现在让我们开始安装Composer,PHP的包管理器。
从官网下载安装程序然后进行安装:
1 2 |
~$ curl -sS https://getcomposer.org/installer -o composer-setup.php ~$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer |
使用下面的命令验证composer的安装:
1 |
~$ composer |
应该可以看到如下输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/ ____/___ ____ ___ ____ ____ ________ _____/ / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / \____/\____/_/ /_/ /_/ .___/\____/____/\___/_//_/ 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 |
2、初始化Laravel 5.8项目
生成一个Laravel 5.8项目非常简单,在终端输入如下命令:
1 |
~$ composer create-project --prefer-dist laravel/laravel crud-app |
上述命令将安装laravel 5.8.3。可以使用下面的命令来验证安装的版本:
1 2 3 |
~$ cd crud-app ~/crud-app$ php artisan -V Laravel Framework 5.8.19 |
3、安装Laravel项目的前端依赖库
在生成的Laravel项目中,package.json文件包含了前端依赖库的描述信息,例如:
- axios
- bootstrap
- cross-env
- jquery
- laravel-mix
- lodash
- popper.js
- resolve-url-loader
- sass
- sass-loader
- vue
使用npm命令安装这些前端依赖库:
1 |
~/crud-app$ npm install |
npm命令执行完之后,在目录中将会出现node_modules目录。
4、创建MySQL数据库
现在我们来创建一个MySQL数据库来保存数据。在终端启动mysql客户端 并在提示时输入密码,然后进入mysql控制台:
1 |
~$ mysql -u root -p |
在mysql控制台输入下面的SQL语句创建db数据库:
1 |
mysql> create database db; |
打开.env文件来更新访问MySQL数据库的账号信息:
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=db DB_USERNAME=root DB_PASSWORD=****** |
现在,可以运行migrate
命令来创建Laravel需要的SQL数据表了:
1 |
~/crud-app$ php artisan migrate |
5、创建第一个Laravel模型
Laravel使用MVC架构模式来将应用解耦为三个部分:
- 模型Model用来封装数据访问层
- 视图View用来封装表示层
- 控制器Controller用来封装应用控制代码并负责模型和视图的通信
现在让我们来创建第一个Laravel模型,在终端输入如下命令:
1 |
~/crud-app$ php artisan make:model Contact --migration |
上面的命令将创建一个Contact模型以及一个迁移文件,在终端中我们得到 类似下面这样的输出:
1 2 |
Model created successfully. Created Migration: 2019_01_27_193840_create_contacts_table |
打开迁移文件database/migrations/xxxxxx_create_contacts_table进行 相应的更新:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?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');} } |
我们再contracts表中添加这些字段:first_name、last_name、email、job_title、 city 和 country 。
现在可以使用下面的命令在数据库中创建contracts表:
1 |
~/crud-app$ php artisan migrate |
现在让我们看一下Contract模型,我们将使用它来和contracts数据表交互。打开 app/Contact.php 并参考以下内容进行更新:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Contact extends Model {protected $fillable = ['first_name','last_name','email','city','country','job_title' ]; } |
6、创建Laravel控制器和路由
在创建模型并执行数据迁移后,现在我们创建与Contract模型协同工作的 控制器和路由。在终端运行下面的命令:
1 |
~/crud-app$ php artisan make:controller ContactController --resource |
打开app/Http/Controllers/ContactController.php,初始内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?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){//} } |
ContractController类继承自Laravel的Controller类,并且定义了 一组方法用于对Contact模型的CRUD操作。现在我们需要实现这些方法。 不过在实现这些方法之前,让我们先添加路由。
打开routes/web.php,参考如下内容进行修改:
1 2 3 4 5 6 |
<?php Route::get('/', function () {return view('welcome'); });Route::resource('contacts', 'ContactController'); |
使用Route的resource()静态方法,你可以创建多个路由来暴露 资源的多种访问操作。这些路由都映射到ContactController的不同 方法上(我们随后将实现这些方法):
- GET/contacts:映射到index()方法
- GET /contacts/create:映射到create()方法
- POST /contacts:映射到store() 方法
- GET /contacts/{contact}:映射到show()方法
- GET /contacts/{contact}/edit: 映射到edit()方法
- PUT/PATCH /contacts/{contact}:映射到update()方法
- DELETE /contacts/{contact}:映射到destroy()方法
这些路由用于提供HTML模板,同时也用作Contract模型的API端结点。
7、实现CRUD操作
现在让我们实现控制器的方法。
7.1 C - Create/创建操作
ContactController包含了映射到POST /contracts
端结点的store()
方法, 该方法将用来在数据库中创建一个联系人/contact,映射到GET / contracts/create
的create()
方法将用来提供HTML表单。仙子我们来实现这两个方法。
首先重新打开app/Http/Controllers/ContactController.php ,导入Contact模型:
1 |
use App\Contact; |
接下来,找到store()方法进行如下修改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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!'); } |
然后,找到create()方法进行如下修改:
1 2 3 4 |
public function create() {return view('contacts.create'); } |
create()
函数使用view()
方法来返回reousrces/view
目录中的create.blade.php
模板。
在创建create.blade.php
模板之前,我们需要创建一个基础模板,create以及本教程中的 其他模板都将继承这个基础模板。
在resources/views
目录中,创建base.blade.php
文件:
1 2 |
~/crud-app$ cd resources/views ~/crud-app$ touch base.blade.php |
打开resources/views/base.blade.php,添加如下模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <html lang="en"> <head><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Laravel 5.8 & 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> |
现在我们创建create.blade.php模板。首先在views目录创建一个contracts文件夹:
1 |
~/crud-app/views$ mkdir contacts |
然后创建模板:
1 2 |
~/crud-app/views$ cd contacts ~/crud-app/views/contacts$ touch create.blade.php |
打开resources/views/contacts/create.blade.php,添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
@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><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 |
表单效果如下:
7.2R - Read/读取操作
现在让我们读取并显示MySQL数据库中的联系人信息。
打开app/Http/Controllers/ContactController.php文件,找到index()
方法并进行 如下修改:
1 2 3 4 5 6 |
public function index() {$contacts = Contact::all();return view('contacts.index', compact('contacts')); } |
接下来创建index模板resources/views/contacts.index.blade.php:
1 |
~/crud-app/views/contacts$ touch index.blade.php |
打开resources/views/contacts/index.blade.php 添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
@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 |
7.3 U - Update/更新操作
现在我们实现数据更新操作。打开app/Http/Controllers/ContactController.php 文件,找到edit($id)方法进行如下更新:
1 2 3 4 5 |
public function edit($id) {$contact = Contact::find($id);return view('contacts.edit', compact('contact')); } |
接下来我们实现update()方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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!'); } |
现在需要添加edit模板,在resources/views/contacts/目录中创建edit.blade.php文件:
1 |
~/crud-app/views/contacts$ touch edit.blade.php |
打开文件resources/views/contacts/edit.blade.php,添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
@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 |
7.4 D - Delete/删除操作
最后我们要实现删除操作。打开app/Http/Controllers/ContactController.php文件, 找到destroy() 方法,然后进行如下的更新:
1 2 3 4 5 6 7 |
public function destroy($id) {$contact = Contact::find($id);$contact->delete();return redirect('/contacts')->with('success', 'Contact deleted!'); } |
容易注意到CRUD API方法中重定向到/contacts路由时,传入了一个index模板中没有 的消息,现在让我们来修改。
打开resources/views/contacts/index.blade.php文件,找到如下代码:
1 2 3 4 5 6 7 8 |
<div class="col-sm-12">@if(session()->get('success'))<div class="alert alert-success">{{ session()->get('success') }} </div>@endif </div> |
我们还需要添加一个按钮:
1 2 3 |
<div><a style="margin: 19px;" href="{{ route('contacts.create')}}" class="btn btn-primary">New contact</a> </div> |
页面效果如下:
原文链接:Laravel 5.8 Tutorial: Build your First CRUD App with Laravel and MySQL (PHP 7.1+)
Laravel 5.8简明教程相关推荐
- python简明教程word版-计算机开放电子书归档 2018
97 Things Every Programmer Should Know A Java Reference (UCB CS61b Textbook) AI Cheat Sheet Advanced ...
- CGIC简明教程(转摘)
CGIC简明教程 本系列的目的是演示如何使用C语言的CGI库"CGIC"完成Web开发的各种要求. ********************************* 基础 ...
- kangle web server源代码安装简明教程
kangle web server源代码安装简明教程 - kangle使用交流 - kangle软件 是一款高性能web服务器,反向代理服务器,提供虚拟主机管理系统及代理服务器,web服务器架设 - ...
- CentOs6.5中安装和配置vsftp简明教程
这篇文章主要介绍了CentOs6.5中安装和配置vsftp简明教程,需要的朋友可以参考下 一.vsftp安装篇 复制代码代码如下: # 安装vsftpd yum -y install vsftpd # ...
- sqlalchemy mysql_SQLAlchemy简明教程
原文可见:SQLAlchemy简明教程 - Jiajun的编程随想 SQLAlchemy是Python中常用的一个ORM,SQLAlchemy分成三部分: ORM,就是我们用类来表示数据库schema ...
- python tcp server_python scoket 编程 | tcp server client - 简明教程
TCP 和 UDP 的区别 这两个协议都是传输层的协议,解决的问题,都是端口与端口的通信问题. TCP 每次建立通信,都需要三次握手,确定双方状态完毕,在发送数据.如果发送的数据出现了异常,TCP 也 ...
- 简明python教程pdf-python简明教程中文pdf
python简明教程中文pdf电子书是作者通过自己对计算机语言多年来的研究和学习得出的学习经验,对于python新手来说非常有用,值得大家下载学习. python简明教程中文pdf文章目录 1.介绍 ...
- 简明python教程在线-Python简明教程
Python简明教程在线阅读地址: https://bop.molun.net/ DocStrings 该文档字符串所约定的是一串多行字符串,其中第一行以某一大写字母开始,以句号结束.第二行为空行,后 ...
- linux 防火墙iptables简明教程
前几天微魔部落再次遭受到个别别有用心的攻击者的攻击,顺便给自己充个电,复习了一下linux下常见的防火墙iptables的一些内容,但是无奈网上的很多教程都较为繁琐,本着简明化学习的目的,微魔为大家剔 ...
最新文章
- 空函数有参函数调用参数的注意事项Swift 1.1语言
- TCP/IP / PDU 是什么
- 无法检测的新型 Linux 恶意软件利用 Dogecoin API 攻击 Docker 服务器
- [转]jQuery: how to get which button was clicked upon form submission?
- Scrapyd发布爬虫的工具
- ELK日志搜索平台搭建
- 泰克吉时利Keithley数据采集器自动计量校准软件NSAT-3070
- 计算机系统常见故障分析与排除,电脑常见网络故障分析与排除方法
- Ruby在Windows下安装
- 华为matebooke能装鸿蒙系统吗,华为matebook e安装系统
- 什么是视频结构化?视频结构化有什么作用
- 【SDOI2015】星际战争(网络流)
- 冲击港交所:百果园书写水果连锁运营默示录
- Meyer Burger获中国客户1800万瑞士法郎光伏设备订单
- Opencv入门(播放AVI视频)
- 浏览器自动化操作(Web Browser Automation)(一)
- 在Linux上解压缩和打包WAR文件
- MPAndroidChart实现曲线阴影效果
- 关于Jonathan S. Weissman与RIT(罗切斯特理工学院,位于纽约)
- CC2530简单功能实现