梦入琼楼寒有月,行过石树冻无烟

📖 earlier posts 📖

Laravel Factory SQL

Laravel 为开发者提供了 Factory解决数据库的创建以及填充,这也在Laravel v6中被称之为“数据库测试”,但本文中主要根据实际情况来创建一个模型工厂(Model factory)。模型工厂主要用于来新建数据库和相应的模型,最后映射在数据库中,当然也可以进行数据库的随机填充。

如果将 Laravel Factory 与 Java Spring boot 相比的话,单纯通过数据库映射来进行比较,因为 Spring 是根据你在运行时直接判断是否创建字段和数据库的,如果配置正确则在运行时直接给你创建,相比之下 Spring 还是较为方便的。但是如果根据总体功能来将,Laravel Factory 将会更上一层,因为其默认将 fakerr 库作为依赖项,即随着 Laravel 一起进行提供,因此 Factory 还可以对数据库进行随机填充

创建模型

在此之前,希望您已经配置了数据库相关的文件,如数据库名称(dataname)、帐号(username)、密码(password)等配置的正确,以及已经成功构建了一个 Laravel 项目并保证php artisan serv可以正确的运行,在此之后您可以进行新建工厂的步骤(create factory)。

artisan make:model Issues -m``` 通过使用 make:model 来创建一个模型,之后会在 **/database/migrations/** 下创建一个名为“2021_05_07_002215_create_issues_table.php”的文件,以及在```app/```路径下新建一个**Issues.php**文件,我们可以通过```2021_05_07_002215_create_issues_table.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

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateIssuesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('issues', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('titles');
$table->dateTime('datetimes');
$table->text('names');
$table->text('category');
$table->text('harms');
$table->text('paths');
$table->text('types');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('issues');
}
}

对应的数据库命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
create table issues
(
id bigint unsigned auto_increment
primary key,
titles text not null,
datetimes datetime not null,
names text not null,
category text not null,
harms text not null,
paths text not null,
types text not null,
created_at timestamp null,
updated_at timestamp null
)
collate = utf8mb4_unicode_ci;

映射数据库

1
2
3
php artisan migrate
Migrating: 2021_05_07_002215_create_issues_table
Migrated: 2021_05_07_002215_create_issues_table (0.02 seconds)

当我们创建完模型(create model)之后,需要通过使用php artisan migrate来映射到数据库中,此时数据库将会生成并创建一个名为issues的数据表,在此下包含了对应的字段名称和相应类型。

Laravel Blade

在Laravel Blade内,官方所提供了一个简洁且优雅的前端模板引擎,他允许你在blade.php文件内写入html以及PHP代码,他因为所有Blade语法都会被编译成正常的PHP代码并缓存,所以速度会稍微快那么一点。除非在此修改,某则Blade模板将不会在此进行编译,在一般的情况下都会将会存放在/resouces/views目录内。

模板继承

在Laravel blade内,模板继承是常见的一种,这种写法在Laravel oauth内使用中,其语法和隔壁Thymeleaf模板引擎更加的简单,其中主要分为定义@section以及@yield显示等。Laravel内,以“@”为开头的将会被称之为“指令”,通过指令我们可以实现继承、循环、判断等。

@section……@show and @yield

index

1
2
3
4
5
6
7
8
9
10
11
{{-- index.blade.php --}}
<html>
<head>
<title>index - @yield('title')</title>
</head>
<body>
@section('h1')
<p>Hello,world!</p>
@show
</body>
</html>

inbar

1
2
3
4
{{inbar.blade.php}}
@extends('index')
@section('title','inbar')
@section('h1','Hello,inbar')

在模板继承中,我们主要使用了@yield以及@section指令,其中@yield 用于显示内容 ,而 @section 将会被用于定义一部分内容。所以在index.blade.php内,在<title>标签中使用了@yield即显示”title”内容,所以在inbar.blade.php内容由”@section”所指定定义了title -> inbar所以与index、inbar所组合后的index- inbar的标题。

而在index.blade.php@section所定义的将会被@section('h1','Hello,inbar')所替换,而以后我们将会介绍如何保留@section所替换掉的内容。

@section……@parent……@endsection

在上述一章中我们介绍了@section……@show……@yield,而此次我们将会增加一个,@parent以及@endsection,这两个指令分别是保留所替换掉的@section以及结束本次替换字段。

index

1
2
3
4
5
6
7
8
9
10
11
{{-- index.blade.php --}}
<html>
<head>
<title>index - @yield('title')</title>
</head>
<body>
@section('h1')
<p>Hello,world!</p>
@show
</body>
</html>

inbar

1
2
3
4
5
6
7
{{-- inbar.blade.php --}}
@extends('index')
@section('title','inbar')
@section('h1')
@parent
<p>Hello,inbar!</p>
@endsection

本文我们通过使用 @parent 来保留使用 @section 指令所替换或覆盖的内容,所以通过使用此指令将会保留覆盖的内容。而@section……@endsection将会使用@section……@endsection来结束替换指令,而不是根据上述使用的@section('h1','Hello,inbar')

@show 与 @endsection

根据官方的解释是在同一模板定义@section时,使用@show,而在子模板即“扩展布局”中使用@endsection作为结尾。在本文同一模板即index.blade.php内,写入任何信息即“同一模板”,而如果在除了以index.blade.php外的则是子模板。

@extends

通过上述介绍,读者得知@extends('index')用于引入和扩展视图扩展到另外一个视图内,即将inbar.blade.php内使用@extends('index')来引入index.blade.php文件。而{{-- code --}}将会用于注释,这与html所使用的<!-- code -->同意。

with …… title (composer)

在Laravel中,我们可以通过使用composer来进行数据的传递以及获取和定义,我们可以通过使用此方法来进行视图(view)、控制器(controller)进行传递。

web.php

1
2
3
Route::get('/', function () {
return view('inbar')->with('title', 'Hello,world');
});

inbar.blade.php

1
{{$title}}

条件与循环语句

条件语法

@php …… @endphp

在众多的教材以及文档中都会教给大家一段 Laravel Blade引擎模板,所以本文将会以一个i前后顺序来介绍@php……@endphp指令:

1
2
3
4
5
6
7
@if (count($value) === 1)
……
@elseif (count($value) === 0)
……
@else
……
@endif

@if……@elseif……@else……@endif

通过上述code你可能会更加疑惑$value是怎么传过去或怎么定义的,此时你会通过使用控制器、路由、视图中进行定义或传入,也许你可以通过使用with来通过路由进行传递,本文我们告知下最为简单的演示@php……@endphp指令的作用。

1
2
3
4
5
6
7
8
9
10
@php
$var = array('1','2')
@endphp
@if (count($var) === 1)
一个数组
@elseif (count($var) >= 2)
大于两个数组
@else
都不是
@endif

我们通过以上code和流程图的演示,可以明显的表示出@php……@endphp来定义一个并富有两个数组分别为“1、2”。经过判断语法是大于两个数组的,所以自然而然的输出为“大于两个数组”

循环语句

@for……@foreach


在Laravel blade模板引擎中,不仅仅为我们提供了一个条件指令@if……@elseif……@else……@endif,自然而然的为开发者提供了一个简单的循环指令@for……@foreach

1
2
3
@for($i = 0;$i < 10;$i++)
共输出 {{$i}} 次<br>
@endfor

Laravel Homestead

Laravel Homestead 由官方所封装对Vagrant box,为开发者所提供来一个完美的开发环境,必须要在本地进行安装相关的PHP开发环境以及相关服务。如果我们在此之前从未接触Laravel,可能会知道Docker,而Laravel我们可以使用Vagrant进行实现。

安装 vagrant

在Laravel内,Vagrant提供一种简单且优雅的方式来管理和配置虚拟主机,而LcaravelHomestead是官方封装的Vagrant box,提供了一个完美的开发环境,并不需要本地安装 PHP以及其他服务器应用。

vagrant install


本文我们将会使用 Arch linux环境进行构建,即pacman软件管理包,在Laravel环境下我们可以非常简单的下载 vagrant,当下载完后我们将会使用 vagrant -v进行检测是否安装成功

下载 box

在使用vagrant box add laravel/homestead时将会出现下载失败的提示,通常你会等待个几个小时甚者挂一晚上的结果都依然是这种问题。所以你需要通过访问或下载:https://vagrantcloud.com/ubuntu/boxes/xenial64/versions/20190101.0.0/providers/virtualbox.box,将下载完后的文件保存。

将下载后的 xenial-server-cloudimg-amd64-vagrant.box 存放在与vagrant一起的目录,所以我们将会进入到vagrant即“/opt/vagrant”下使用

vagrant box add laravel/homestead xenial-server-cloudimg-amd64-vagrant.box

当执行上方命令后,我们会通过使用vagrant box list,来查看导入情况,当出现:laravel/homestead (virtualbox, 0)时即进入下一个步骤。

Laravel Eloquent ORM

Laravel Eloquent ORM即“数据操作”,在前面我们所介绍的数据库当中,使用的是“DB”而Laravel还为我们提供了另一种更加优雅的方式,即”Laravel Eloquent ORM”。如果将两者作为比较的话,那么Laravel所提供的另一种数据库操作方式Laravel Eloquent ORM则更加的安全和优雅,其操作和语法类似与Spring boot 中的JPA,但又与JPA不一样,只能说通过一定的语法来代替SQL语法。

例子

如果你是通过看文档过来的,那你估计可能看得懂,但是不知道基本的流程。如果做比喻的话可能就是只教你做饭,不教你点火,但是你都会做饭,她不告诉你要让你炒什么菜,基本上就是这个意思,本文将会告诉你如何点火,但是基本的做菜知识你还是需要对照“菜谱进行”。

模型

如果你要用Eloquent ORM,首先你需要有一个模型,之后在有一个控制器,就行了。其中模型来定义数据库表以及字段,之后你可以通过数据库映射的方式来建立表,本文通过列举User模型进行测试:

Eloquent ORM所需要的模型我们可以理解为用于操作数据库的一道过程,在模型中你可以定义需要连接的数据库以及表等相关的信息。当然Laravel还为我们提供了多表操作的方式来满足不同环境的需求。

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
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

控制器

控制器就是你可以来对此进行CURD的一系列操作,Laravel Eloquent ORM也支持你进行一系列的Curd操作,本文我们会使用User模型来进行数据库插入的操作(首先你要引入模型use App\User;),模型默认在app\目录下,当然你也可以选择使用模型来实现控制器的操作:

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
<?php

namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostController 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(Request $request)
{
$user = new User();
$user->name='test_name';
$user->email='test_email';
$user->password='test_password';
$user->save();
}

在此之前你要确保已经配置好数据库和映射数据库等操作完善且正常,否则将无法进行下一步操作。

当以上步骤完成之后,你可以在当前项目下执行php artisan migrate来将数据库迁移到本地数据库内。此时你会产生疑惑,数据库表是从那里来的?答案是在database/migrations目录下的create_user_table.php、create_password_resets.php、create_ailed_jobes_table.php类定义的。

web

1
Route::get('/input/test', 'PostController@create');


此时当你访问http://127.0.0.1:8000/input/test的时候,已经将在控制器所定义的信息插入到了你的数据库之中。

自定义

模型


在本文中,我们可以通过使用php artisan make:model Tesst来定义一个Laravel模型,最终定义完模型之后将会生成在app目录下,我们可以让模型与数据库进行关联,其中可分为两大部分,分别为:

  1. 库:如果当前项目或个人有多个数据库之间对操作我们可以定义多个数据库且指定数据库进行操作;
  2. 表:定义完库之后我们自然就需要来定义表,一个数据库中可能存在多个表所以我们需要来指定一个表进行操作。

Tesst.php

数据表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tesst extends Model
{
/*
* @var string
* $table 指定数据库表
*/
protected $table = 'users';
}

在默认对情况下我们并没有设置Tesst模型到底使用那些表以及那些数据库,所以我们需要明确对指定数据库以及数据表来进行下一步的操作。

数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tesst extends Model
{
/*
* @var string
* $connection 指定 config/databases.php下所定义的数据库链接名称
* $table 指定数据库表
*/
protected $connection = 'mysql';
protected $table = 'users';
}

在默认对情况下,Eloquent模型将会使用其config/databases.php或.env所定义的数据库表,如果有需要我们可以定义多个数据库连接和表,之后在模型中进行指定链接:

config/databases.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'test'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'toor'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
模型名称约定
蛇型命名方法

蛇型命名方法是Python以及php和一些开发语言之中常用对命名方式之一,其在Laravel也可在很多地方见到如:'host' => env('DB_HOST', '127.0.0.1'),,其中DB_HOST就属于蛇型命名方式。

驼峰命名方式

驼峰命名方式在Laravel并不常见,如果读者有接触过Spring boot Data JPA就非常了解驼峰对命名格式TestHost

控制器

PostController.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
<?php

namespace App\Http\Controllers;
use App\Tesst;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostController 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(Request $request)
{
$Tessts = new Tesst();
$Tessts->name='test_namess';
$Tessts->email='test_emailss';
$Tessts->password='test_passwordss';
$Tessts->save();
}

CURD

插入

PostController
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
<?php

namespace App\Http\Controllers;
use App\Tesst;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostController 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(Request $request)
{
$Tessts = new Tesst();
$Tessts->name= $request->input('user');
$Tessts->email= $request->input('email');
$Tessts->password= $request->input('password');
$Tessts->save();
}
input.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
User:<input type="text" name="user" />&nbsp;
Email:<input type="text" name="email" />
Password:<input type="text" name="password" />

<input type="submit" value="up">
</form>
</body>
</html>

web.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/input', function () {
return view(('input'));
});

Route::post('/input/test', 'PostController@create');
删除

PostController
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
<?php

namespace App\Http\Controllers;
use App\Tesst;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostController 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(Request $request)
{
$Tessts = new Tesst();
Tesst::find($request->input('id'))->delete();//按主键删除
$Tessts->forceDelete();
}
input.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Id:<input type="text" name="id" />&nbsp;
<input type="submit" value="up">
</form>
</body>
</html>

在Laravel的官方文档之中,关于删除有两种写法,分别为通过主键删除和软删除两种,本文所使用的是通过主键“id”进行删除,当然你也可以选择软删除。

关于软删除本文将不会进行列举,软删除和通过主键删除唯一不同的则是当你使用软删除的时候不会真的在数据库中删除数据,而是在模型中设置一个deleted_at对属性插入数据库,如果模型中有一个非空的delete_at值,那么说明该模型已经被软删除了。

修改

PostController
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
<?php

namespace App\Http\Controllers;
use App\Tesst;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostController 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(Request $request)
{
$Tessts = Tesst::find($request->input('id'));
$Tessts->name=$request->input('name');
$Tessts->save();
}
input.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Id:<input type="text" name="id" />&nbsp;
Name:<input type="text" name="name" />
<input type="submit" value="up">
</form>
</body>
</html>

查询

PostController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

namespace App\Http\Controllers;
use App\Tesst;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$Tessts = Tesst::all();
return view('input',['Tessts'=>$Tessts]);
}
input.blade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<table border="1">
<tr>
<td>Id</td>
</tr>
@foreach ($Tessts as $flight)
<tr>
<td>{{$flight->name}}</td>
</tr>
@endforeach
</table>
</body>
</html>

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/input/test', 'PostController@create');

在以上对实例之中,关于PostController.php类来实现增删改查对操作方法处写的并不对,关于CURD增删改查Laravel框架可生成一个CURD模板来规定删除写在……方法下、查询写在……方法下、创建写在……方法下、更新写在……方法下。我们可以通过使用php artisan make:controller PostController --resource来创建一个CURD增删改查的模板。

Laravel 用户认证

在Laravel 6.v当中,为我们提供了一个与以往不同的认证模块,即Laravel/ui,Laravel/ui主要提供了用户认证视图以及Laravel的支持等,以及配合Laravel自带的邮件发送功能实现了用户注册、用户登录、用户验证以及保护路由等。

构建项目

在使用Laravel/ui之前,我们需要构建一个Laravel项目且保证可以正常的运行和访问即可执行下一步操作:

composer create-project laravel/laravel=”6.0” test_webapp

Laravel/ui


写到这一些读者特别是使用过Laravel 5左右的读者就会产生疑问,Laravel不是使用 Larave/auto?为什么到Laravel 6就变成了Laravel/ui了,因为Laravel默认自带了一套Laravel auto,所以我们只需要下载Laravel/ui来进行访问即可:

composer require laravel/ui “^1.0” –dev
php artisan ui vue –auth

数据库迁移

所谓数据库迁移,就是说你在php类当中定义过的数据库字段以及表迁移到你本地的数据库之中,在迁移的之前,我们需要修改其数据库配置文件:

.env

如果当前项目没有.env文件,且通过git形式进行拉去的,你需要通过cp .env.axample .env进行重构env文件,之后配置其数据:

1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=toor

database.php

database.php类在config目录下,我们需要更改其mysql的配置信息主要包括数据库、账号、密码、等:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'test'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'toor'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],


当以上步骤完成之后,你可以在当前项目下执行php artisan migrate来将数据库迁移到本地数据库内。此时你会产生疑惑,数据库表是从那里来的?答案是在database/migrations目录下的create_user_table.php、create_password_resets.php、create_ailed_jobes_table.php类定义的:

1
2
3
4
5
6
7
8
9
10
11
12
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

邮件样式与布局


当我们使用后发现,Laravel为我们提供的功能还包括了密码重置、邮件发送等功能,所以我们需要修改其SMTP配置与邮件样式:

SMTP 支持

在Laravel之中,我们需要修改SMTP的支持配置文件分别为.env、mail.php两个配置文件内信息:

1
2
3
4
5
6
MAIL_DRIVER=smtp
MAIL_HOST=smtp.xxx.xxxx.com
MAIL_PORT=25
MAIL_USERNAME=oa@zsun.org.cn
MAIL_PASSWORD=xxxx
MAIL_ENCRYPTION=null
config/mail.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<?php

return [

/*
|--------------------------------------------------------------------------
| Mail Driver
|--------------------------------------------------------------------------
|
| Laravel supports both SMTP and PHP's "mail" function as drivers for the
| sending of e-mail. You may specify which one you're using throughout
| your application here. By default, Laravel is setup for SMTP mail.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/

'driver' => env('MAIL_DRIVER', 'smtp'),

/*
|--------------------------------------------------------------------------
| SMTP Host Address
|--------------------------------------------------------------------------
|
| Here you may provide the host address of the SMTP server used by your
| applications. A default option is provided that is compatible with
| the Mailgun mail service which will provide reliable deliveries.
|
*/

'host' => env('MAIL_HOST', 'smtp.ym.163.com'),

/*
|--------------------------------------------------------------------------
| SMTP Host Port
|--------------------------------------------------------------------------
|
| This is the SMTP port used by your application to deliver e-mails to
| users of the application. Like the host we have set this value to
| stay compatible with the Mailgun e-mail application by default.
|
*/

'port' => env('MAIL_PORT', 25),

/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/

'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'oa@zsun.org.cn'),
'name' => env('MAIL_FROM_NAME', "钟山计算机端口安全联合审核平台"),
],

/*
|--------------------------------------------------------------------------
| E-Mail Encryption Protocol
|--------------------------------------------------------------------------
|
| Here you may specify the encryption protocol that should be used when
| the application send e-mail messages. A sensible default using the
| transport layer security protocol should provide great security.
|
*/

'encryption' => env('MAIL_ENCRYPTION', 'tls'),

/*
|--------------------------------------------------------------------------
| SMTP Server Username
|--------------------------------------------------------------------------
|
| If your SMTP server requires a username for authentication, you should
| set it here. This will get used to authenticate with your server on
| connection. You may also set the "password" value below this one.
|
*/

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

/*
|--------------------------------------------------------------------------
| Sendmail System Path
|--------------------------------------------------------------------------
|
| When using the "sendmail" driver to send e-mails, we will need to know
| the path to where Sendmail lives on this server. A default path has
| been provided here, which will work well on most of your systems.
|
*/

'sendmail' => '/usr/sbin/sendmail -bs',

/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/

'markdown' => [
'theme' => 'default',

'paths' => [
resource_path('views/vendor/mail'),
],
],

/*
|--------------------------------------------------------------------------
| Log Channel
|--------------------------------------------------------------------------
|
| If you are using the "log" driver, you may specify the logging channel
| if you prefer to keep mail messages separate from other log entries
| for simpler reading. Otherwise, the default channel will be used.
|
*/

'log_channel' => env('MAIL_LOG_CHANNEL'),

];

邮件样式

在默认的情况下,邮件样式存储在Laravel项目中的\vendor\laravel\framework\src\llluminate\Mail\rsources目录下,我们可以通过以下两个命令让其创建在/resources/views/vendor文件下:

php artisan vendor:publish –tag=laravel-notifications
php artisan vendor:publish –tag=laravel-mail

之后在resources/views/vendor/mail下将会生成对应的邮件样式,我们可以分别的进行更改CSS以及blode.php模板文件

修改邮件内容

除了文件样式以外我们还可以修改其默认的邮件内容,邮件的内容我们可以通过编辑/vendor/laravel/framework/src/Illuminate/Auth/Notifications内的Php类来实现。

错误信息


如果你觉得Laravel自带的错误验证消息满足不了你的口味或者说你想来点”自定义“,可以通过修改其vendor/laravel/framework/src/Illuminate/Foundation/Auth目录中的类以及app/Http/Controllers/Auth分别进行修改以得到满足。

ResetsPasswords.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;

trait ResetsPasswords
{
use RedirectsUsers;

/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* @param \Illuminate\Http\Request $request
* @param string|null $token
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}

/**
* Reset the given user's password.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());

// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);

// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}

/**
* Get the password reset validation rules.
*
* @return array
*/
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:10',
];
}

/**
* Get the password reset validation error messages.
*
* @return array
*/
protected function validationErrorMessages()
{
return [
'required' => ':attribute 必填',
'email' => '需要以邮箱格式填写',
'min' => '密码需要等于或大于十位数或以上',
'confirmed' => '重复密码不正确',
];
}

/**
* Get the password reset credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function credentials(Request $request)
{
return $request->only(
'email', 'password', 'password_confirmation', 'token'
);
}

/**
* Reset the given user's password.
*
* @param \Illuminate\Contracts\Auth\CanResetPassword $user
* @param string $password
* @return void
*/
protected function resetPassword($user, $password)
{
$this->setUserPassword($user, $password);

$user->setRememberToken(Str::random(60));

$user->save();

event(new PasswordReset($user));

$this->guard()->login($user);
}

/**
* Set the user's password.
*
* @param \Illuminate\Contracts\Auth\CanResetPassword $user
* @param string $password
* @return void
*/
protected function setUserPassword($user, $password)
{
$user->password = Hash::make($password);
}

/**
* Get the response for a successful password reset.
*
* @param \Illuminate\Http\Request $request
* @param string $response
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetResponse(Request $request, $response)
{
return redirect($this->redirectPath())
->with('status', trans($response));
}

/**
* Get the response for a failed password reset.
*
* @param \Illuminate\Http\Request $request
* @param string $response
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetFailedResponse(Request $request, $response)
{
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}

/**
* Get the broker to be used during password reset.
*
* @return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}

/**
* Get the guard to be used during password reset.
*
* @return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}

RegisterController.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
<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/

use RegistersUsers;

/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/home';

/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}

/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:10', 'confirmed'],
], [
'required' => ':attribute 必填',
'string' => ':attribute 需以字符串形式',
'email' => ':attribute 要以邮箱格式',
'min' => ':attribute 最小十位数',
'max' => ':attribute 最大不能超过255位',
'confirmed' => ':attribute 不一致',
'unique' => ':attribute 邮箱冲突',
], [
'name' => "联合团队账号名称",
'email' => '邮箱',
'password' => '密码',
]);
}

/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}

Laravel 数据库

如果我们要开发一个交互性非常强的站点,那么数据库交互就是这其中必不可少的一项,在目前,Laravel主要支持四种主流的数据库分别为:“MySQL、PostgreSQL、SQLite、SQL Server”。

配置

在Laravel之中,配置数据库主要可以通过config/database.php类进行,也可通过配置.env文件来实现,本文我们以配置MySQL为例:

database.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'test'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'toor'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],

.env

1
2
3
4
5
6
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=toor

CURD (增删改查)


在实际的开发项目过程中,对数据库操作最为主要的就是“CURD”即增删改查的一系列操作,对此Laravel为我们提供了一个专门用于进行CURD操作的控制器模板,我们可以通过使用命令进行创建:

php artisan make:controller PostController –resource

之后创建的数据库CURD模板将会自动在app/Http/Controllers目录下生成,至控制器的信息我们可以重新回顾下6.Laravel 控制器所学的知识。

插入数据

在Laravel之中,我们可以引入DB扩展中的insert方法来进行插入,且支持多数据插入如下:

input.blode.php

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Username:<input type="text" name="id" />&nbsp;
<input type="submit" value="up">
</form>
</body>
</html>

PostController

1
2
3
4
5
6
7
8
9
10
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$id = $request->input('id');
DB::insert('insert into user(id) value(?)', [$id]);
}

web.app

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/input', function () {
return view(('input'));
});

Route::post('/input/test', 'PostController@create');

删除数据


在增删改查中,删除数据排第二,也是一项非常常用的需求,通常只有管理员权限才可以做到这种功能,如果使用Laravel来实现的话需要delete方法:

PostController

1
2
3
4
5
6
7
8
9
10
11
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Request $request)
{
$id = $request->input('id');
DB::delete('delete from user where id = ?',[$id]);
}

input.blode.php

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Username:<input type="text" name="id" />&nbsp;
<input type="submit" value="up">
</form>
</body>
</html>

web.php

1
2
3
Route::get('/show', 'PostController@show');

Route::post('/input/test', 'PostController@destroy');

修改数据


在本次的演示当中,我们主要将数据库中的2更改为20,当然由于我们数据库中只有一个”id”字段,如果需要作出指定修改你需要建立两个字段,来进行配合,本次我们只演示如何修改字段数据,可以使用update数据:

PostController

1
2
3
4
5
6
7
8
9
10
11
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Request $request)
{
$id = $request->input('id');
DB::update('update user set id=?',[$id]);
}

input.blude.php

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Username:<input type="text" name="id" />&nbsp;
<input type="submit" value="up">
</form>
</body>
</html>

web.php

1
2
3
4
5
Route::get('/input', function () {
return view(('input'));
});

Route::post('/input/test', 'PostController@edit');

查询数据


对于Laravel的数据查询,也是一项非常简单且优雅的语法形式,其主要使用select方法进行查询:

PostControoller

1
2
3
4
5
6
7
8
9
10
11
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show()
{
$users = DB::select('select * from user');
return view('input', ['users'=>$users]);
}

input.blade.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<table border="1">
<tr>
<td>id</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{$user->id}}</td>
</tr>
@endforeach
</table>
</body>
</html>

web.php

1
Route::get('/show', 'PostController@show');

Laravel 表单验证

在Laravel之中提供了很多种不同的方法来验证表单所传入的数据,在默认的情况下Laravel会使用基本的控制器类validatesRequest所定义的,该类提供了各种强大的验证规则来验证所传入的HTTP请求:

表单传输方式

通常我们会验证表单的传输方式分别为POST或是GET,对此Laravel为我们提供了一个isMethod方法来进行验证,我们可以在路由中进行也可在控制器中进行,本文为了简约流程所以使用路由进行:

web.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
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/input', function () {
return view(('input'));
});

Route::post('/input/test', function (Request $request) {
if ($request->isMethod('post')) {
echo "yes";
} else {
echo "no";
}
});

input.blode.php

1
2
3
4
5
6
7
8
9
10
11
12
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<form action="/input/test" method="post">
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Username:<input type="text" name="username" />&nbsp;
<input type="submit" value="up">
</form>
</body>
</html>

验证规则

控制器

通常在原生态的PHP语言之中,验证规则通常会使用正则表达式等方式,但是由于正则表达式不宜于阅读,所以Laravel为我们提供了一种更好的validate方法,主要分为制定规则、错误回显、表单命名等。如果传入的请求参数未通过指定的验证规则,Laravel 则会将用户重定向到之前的位置中,并且将错误信息存储至 session中。

变量由 ```Iliumineat\View\middleware\ShareErrorsFormSession```中间件绑定至视图当中,当这个中间件被使用会就可一在视图获取到 ```$error```变量(在理论上来将 $error 可以被安全的使用)
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

```php
// input.blode.php
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<!--
这里主要用于返回错误信息
-->
@if($errors->any())
<div class="alert alert-danger">
@foreach($errors->all() as $error)
<p>{{$error}}</p>
@endforeach
</div>
@endif

<form action="/input/test" method="post">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
Username:<input type="text" name="username" />&nbsp;
<input type="submit" value="up">
</form>
</body>
</html>
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
// TestController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
public function store(Request $request) {
print_r($request->all());
$this->validate($request, [
/*
* 用于定义规则
*/
'username'=>'required|max:1|alpha',
], [
/*
* |- 大类
* | |- required 必填
* | |- max 最大
* | |- min 最小
* | |- integer 数值
*/
'required' => ':attribute 必填',
'max' => ':attribute 长度不能大于一个字符',
'alpha' => ':attribute 只能包含字母',
], [
/*
* |- 用于给input表单进行命名,时候后会输出
* | |-"账号名称 必填"
* |- 如果不使用则会输出
* | |- username 账号名称
*/
'username' => '账号名称',
]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 web.php
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/input', function () {
return view(('input'));
});

Route::post('/input/test', 'TestController@store');

返回错误信息

返回全部错误信息

如果传入的请求参数未通过指定的验证规则,Laravel 则会将用户重定向到之前的位置中,并且将错误信息存储至 session中。

$error 变量由 Iliumineat\View\middleware\ShareErrorsFormSession中间件绑定至视图当中,当这个中间件被使用会就可一在视图获取到 $error变量(在理论上来将 $error 可以被安全的使用)

1
2
3
4
5
6
7
@if($errors->any())
<div class="alert alert-danger">
@foreach($errors->all() as $error)
<p>{{$error}}</p>
@endforeach
</div>
@endif

在上述的 code 中,主要可以返回全部的错误信息,假设表单1、表单2为通过验证规则,则会将这两个表单的错误信息显示在一个标签之中。

返回单个错误信息
1
2
3
4
@error('titles')
<p>{{$message}}</p>
@enderror
<textarea class="issue-textarea @error("titles") is issue-orss @enderror" rows="1" name="titles"></textarea>

返回单个信息有好处也有缺点,好处就是我们可以通过返回的单个信息来设置显示 如果该表单为通过验证时的样式,而缺点则是 需要一个一个的写

验证表单请求

创建一个请求类

面对更繁杂的表单验证,可以通过创建一个 表单请求 来处理表单验证的逻辑,该请求类是包含验证是的验证逻辑,通常可以通过下述 Artisan 命令进行创建。

1
php artisan make:request StoreTestPost

创建之后该请求类将会存放在 app/Http/Requests/ 目录下,我们分别可以通过 authorize、rules、messages、attributes 来对请求类进行一系列的设置和操作:

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
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreTestPost extends FormRequest
{
/**
* 确定用户是否有权提出此请求。
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}

/**
* 获取应用于请求的验证规则。
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'test' => 'required',
];
}

/*
* 为规则写入提示信息
* Write prompt information for rules
*/
public function messages() {
return [
'required' => ':attribute必填',
];
}

/*
* 为表单设置名称
* Set a name for the form
*/
public function attributes()
{
return [
'test' => "测试",
];
}
}

需要注意的是我们还需要修改当前的控制器,将请求改为表单请求:

1
2
3
4
5
6
7
8
9
10
/**
* Store a newly created resource in storage.
*
* @param StoreTestPost $request
* @return \Illuminate\Http\Response
*/
public function store(StoreTestPost $request)
{
//
}
1
2
//web.php
Route::post('/upload',"PostController@store");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@if($errors->any())
<div>
@foreach($errors->all() as $error)
<p>{{$error}}</p>
@endforeach
</div>
@endif
{{--inbar.blade.php--}}
<form action="/upload" method="post" enctype="multipart/form-data">
@csrf
<input type="hidden" name="_token" value="<?php echo csrf_token()?>">
<input type="text" name="test">
<button type="submit">Up File</button>
</form>

当前语言下的错误提示信息

如果你的需求只是简单的想将 表单所提示的错误信息 改成你想要的,那么通过编辑 resources/lang/en/validation.php 文件也是一个非常好的选择,除此之外它还可以通过attributes支持自定义的表单名称。

Laravel 目前支持的验证规则

DA FA DA
accepted 验证必须是yes\on\1\true 可以运用在服务条款
active_url 验证字段是有效的A或aa记录
after:date 必须是指定日期之后的值
after_or_equal:date 验证字段是指定日期之后与此日期相同的值
alpha 验证必须是由字母组成的数据
alpha_dash 允许包含字母、数字以及破折号和下划线的数据
alpha_num 必须完全是字母或数字的数据
array 验证数据是一个php数组
bail 在第一次验证失败后停止验证规则
before:date 这个验证的数据必须是指定的日期值
before_or_equal:date 验证数据必须是在指定日期之前或相同的日期
between:min,max 安正数据的大小必须在min和max之间
boolean 验证数据必须可以转换为boolean类型 接受true、false、1、0
confirmed 验证数据必须具有匹配字段 验证字段为password,输入必须存在匹配的password字段
date 根据php函数,验证必须是有效的日期
date_equals:date 验证数据必须等于指定日期
date_format:format 验证数据必须匹配指定的日期格式
different:field 验证的数据必须与field值不同
digits:value 验证数据必须为numeric 且必须具有准确长度的value
dimensions u验证文件必须是图片且比例符合规则 min_width:x,min_height=n
ditinct 验证数组时数据不允许有任何重复
email 验证数据符合e-mail地址格式
ends_with:foo,bar 验证数据必须是指定值内的结尾
exists:table,column 验证数据必须存在指定的数据库表中
file 验证数据必须是成功上传的文件
filled 验证数据的存在时不可为空
ge:field 验证数据必须大于指定的field 两个数据必须是相同的类型
gte:field 验证数据必须大于或等于指定的fileld
image 验证数据必须为图片
in:foo,bar 雅正数据必须包含在指定的值列表中
in_array:anotherfield.* 验证数据必须存在与另一个字段antherfield值中
integer 验证数据必须时整数
ip 验证数据必须是ip地址 ip
ipv4 验证数据必须是ipv4地址 ip
ipv6 验证数据必须是ipv6地址 ip
json 验证数据必须是有效的json字符串
lt:field 验证数据必须是指定的field
lte_field 验证数据必须小于或等于指定的数据
max:value 验证数据必须小于或等于给定的值
mimetypes:text/plain 验证文件必须具备列出的其中一个扩展匹配的MIME类型
mimes:foo,bar 验证文件必须是具有列出其中一个扩展名对应的mime类型 mimes:jpeg,png
min:value 验证数据必须具有最小值
not_in:foo,bar 验证数据不能包含在指定的值列表中
not_regex:pattern 验证数据必须与值idngd正则表达式不匹配
nullable 验证数据可以为null
memeric 验证数据必须为数值
password 验证中的数据必须与经过身分验证的用户密码进行匹配
present 验证数据必须存在输入的数据中 可以为空?
regex:pattern 验证数据必须与指定的正则表达式进行匹配
required 验证的字段必须存在于输入的数据中,而不是为空 值为null、值为空字符串、无路径的上传文件
required_if:anotherfield,value_one,value_two 如果其他数据为任意一值,此验证数据必须存在且不为空
required_unless:anotherfield,value 如果数据不等于任意值,此验证数据必须存在且不可为空
required_with:foo,bar 在其他任意指定数据出现时,验证的数据必须存在且不可为空
required_with_all:foo,bar 只有在任意一段数据全部出现时,验证数据才必须存在且不为空
reqrequired_without:foo,bar 在其他数据不出现时,验证数据才存在且不可为空
required_without_all:foo,bar 只有在其他指定数据字段全部不出现时,验证数据才可存在且不可为空
same:field 验证数据必须与指定数据相匹配
size:value 验证数据必须指定值大小一致
starts_with:foo,bar 验证数据必须以指定值之一开头
string 验证数据必须是一个字符串
timezone 验证数据必须符合php函数所定义的有效时区标识 timezoune_identifiers_list
unique:table,column,except,idColumn 验证数据在指定数据库表中是唯一的

Laravel Session

Session即会话控制,主要将客户端的信息存储于cookie之中,这也将会带来很多问题,如果客户端禁用了cookie支持,那么session也将被禁用。在Laravel之中,Session主要提供了一种在多请求之间存储有关用户信息的方法。

Session的配置文件主要存储在config/session.php文件之中,默认的情况下session驱动四file,在生产环境中可以考虑使用memcached或是redis进行驱动,为此Leravel自带了以下几个开箱即用的驱动:

  1. file:将session存储在storage/framework.session;
  2. cookie: 将cookie存储在加密的cookie之中;
  3. database:Session将会被存储在关系型数据库之中;
  4. memcached and redis:将session存储在基于高速缓存的存储系统内;
  5. arrar:将session存储在php数组之中,但是不会被持久化。

检索 session


对于session的检索,Laravel为我们提供了一个非常友好且简洁的get方法,使用该方法可以获取指定的session信息:

web.php

1
2
3
4
5
6
7
use Illuminate\Http\Request;

Route::get('/url', function (Request $request) {
$value = $request->session()->get('_token');
print_r($value);
echo '<br>';
});

获取当前所有的 session


在Laravel框架内,如果要检索所有的数据,我们可以使用Laravel session所提供的all方法来检索所有会话数据:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url', function (Request $request) {
$session = $request->session()->all();
print_r($session);
});

判断是否存在


在以上示例内我们主要介绍了如何获取当前的session数据,所以本次我们需要进行判断该session是否存在,如果返回yes即说明存在,返回no即不存在,本次我们主要使用exiets以及has分别进行演示:

exists

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
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url', function (Request $request) {
// 输出
$session = $request->session()->all();
print_r($session);
echo '<br>';

// 判断
if ($request->session()->exists('_token')) {
echo "yes";
} else {
echo "no";
}
});

has

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
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url', function (Request $request) {
// 输出
$session = $request->session()->all();
print_r($session);
echo '<br>';

// 判断
if ($request->session()->has('_token')) {
echo "yes";
} else {
echo "no";
}
});

存储 session


在此前我们主要介绍了如何查询和判断session相关,那么如果要进行session存储需要如何实现?对此Laravel为我们提供了put方法:

web.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
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url', function (Request $request) {
// 存储
$request->session()->put('jiangxue','Jiang Xue analyzes the open knowledge repository');
session(['key'=>'value']);

// 输出
$value = $request->session()->get('jiangxue');
print_r($value);
echo '<br>';

// 判断
if ($request->session()->has('jiangxue')) {
echo "yes";
} else {
echo "no";
}
});

临时 session


临时session与临时url一样,几乎是只要你刷新过后就会被进行删除,在通常需要实现该功能可能需要很久,对于Laravel·而言,只需要使用flash方法即可:

web.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
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Http\Request;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url', function (Request $request) {
// 存储
$request->session()->flash('jiangxue','Jiang Xue analyzes the open knowledge repository');
session(['key'=>'value']);

// 输出
$value = $request->session()->get('jiangxue');
print_r($value);
echo '<br>';

// 判断
if ($request->session()->has('jiangxue')) {
echo "yes";
} else {
echo "no";
}
});

删除 session


当然,有了存储就有了删除,如何进行删除是一个非常重要的问题,对此Laravel为我们提供了forget方法将用于删除单个session或者多个session:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Route::get('/url', function (Request $request) {
// 存储
$request->session()->put('jiangxue','Jiang Xue analyzes the open knowledge repository');
session(['key'=>'value']);

// 输出
$value = $request->session()->get('jiangxue');
print_r($value);
echo '<br>';

/*
* 删除
* 如需要删除多个可使用 $request->session()->forget(['key_one', 'key_two']);
*/
$request->session()->forget('jiangxue');

// 判断
if ($request->session()->has('jiangxue')) {
echo "yes";
} else {
echo "no";
}
});

Laravel URL

在Laravel框架之中,为我们提供了丰富的url方法,分别可以实现访问、输出、返回、签名等效果的url,本文我们将会使用该方法进行一系列的url演示:

输出url


在Laravel之中,读者最为期待的是输出url信息的方法,使用Laravel框架,输出url方法只需要使用current即可:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Support\Facades\View;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url/{name}', function ($name) {
echo url()->current();
});

获取上一个请求的url


当然,除了获取url,Laravel还为我们提供了另一种用于获取上一个url的方法previous,我们可以通过使用该方法来获取用户上一个页面的url:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Support\Facades\View;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url/{name}', function ($name) {
echo url()->previous();
});

命名url路由


Laravel还为我们提供了一种命名url路由的方式,如果阅读过以往篇幅的读者可能会对此感到熟悉,就是命名路由,可以根据路由名称进行输出对应的信息:

web.php

1
2
3
4
Route::get('/url/{name}', function ($name) {
echo route('url.name',
['name' => $name]);
})->name('url.name');

设置默认值?


当然我们还可以为此设置一个默认值,也就就是说不管你的url是多少,都会输出这个默认值:

web.php
1
2
3
4
Route::get('/url/{name}', function () {
echo route('url.name',
['name' => 'hello']);
})->name('url.name');

URL 签名


在这里面的url签名指的是如果你访问的是localhost:8000/url/111,那么他会修改下url的相关数据如修改成:“http://localhost:8000/url/jiangxue?signature=7ec0cf1d32c6189a1a9b3be402f870427686e5528dd912ceb27e9bc89ed85417”,而生成的这个连接与你直接访问```localhost:8000/url/111```效果是相同的,这项技术也被运用在了邮箱发送与认证当中:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Illuminate\Support\Facades\URL;

Route::get('/', function () {
return view('welcome');
});

Route::get('/url/{name}', function ($name) {
$url = Url::signedRoute('url.name', ['name' => 'jiangxue']);
echo $url;
})->name('url.name');

临时 URL


Laravel对url的支持还远不于以上所列举的方法,为了更好的应用在以上邮箱认证的场景下,Laravel还提供了一个临时的url生成方法temporaySignedRoute就是说他是会变的

web.php

1
2
3
4
5
6
Route::get('/url/{name}', function ($name) {
$url = Url::temporarySignedRoute('url.name', now()->addHour(), [
'name' => 'jiangxue'
]);
echo $url;
})->name('url.name');

Laravel 视图

在Laravel框架中,为我们提供了一个blade.php的后缀扩展名,首先blade.php是由Laravel所提供的一个简单且强大的模板引擎,这与Spring boot所提供的Thyemeleaf类似。blade并不会限制在视图中使用的原生php code,所有blade视图文件都会被编译成原生的php code并将此缓存,除非被再次修改否则将不会被重新编译,并一般情况下存储在resources/views目录下。

路由与视图参数传递


所谓路由与参数进行传递,其实就是获取请求的信息并在blade.app内进行调用其函数并输出后的信息,即路由与视图参数:

web.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
return view('welcome');
});

Route::get('/views/{name}', function ($name) {
return view('views', ['name' => $name]);
});

views.blade.php

1
2
3
4
5
6
7
8
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<h1>Hello,{{$name}}</h1>
</body>
</html>

视图共享


在Laravel之中,如果需要不同之间的视图进行数据的共享,我们可以使用app/Providers/目录下的AppServiceProvider.php类,在boot方法下写入需要共享的函数和参数即可:

AppServiceProvider.php

1
2
3
4
5
6
7
8
9
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->share('date','2021');
}

views.blade.php

1
2
3
4
5
6
7
8
<html>
<head>
<title>This is be Input up</title>
</head>
<body>
<h1>Hello,{{$date}}</h1>
</body>
</html>

判断视图是否存在


Laravel为我们提供了一种针对视图是否存在的方法exists,只需在路由web.php类中进行定义即可:

web.php

1
2
3
4
5
6
7
Route::get('/views', function () {
if (view()->exists('views')) {
echo "yes";
} else {
echo "no";
}
});

自定义错误页面


在Laravel项目之中,可以通过在resources/views/errors内新建各个HTTP状态码的对应blode.php页面,本文主要演示404页面:

404.blode.php

1
2
3
4
5
6
7
8
<html>
<head>
<title>404</title>
</head>
<body>
<h1>404</h1>
</body>
</html>
📖 more posts 📖