Laravel框架 中文文档
PHP >= 7.1.3
OpenSSL PHP
PHP PDO 扩展
PHP Mbstring 扩展
PHP Tokenizer 扩展
PHP XML 扩展
PHP Ctype 扩展
PHP JSON 扩展
php.ini 配置文件需要开启的扩展文件
extension=php_openssl.dll
extension=php_pdo_mysql.dll
extension=php_mbstring.dll
extension=php_fileinfo.dll (验证码代码依赖扩展)
extension=php_curl.dll (主要用于请求的发送)
httpd.conf 配置文件需要开启的模块
Laravel 使用 Composer 来管理项目依赖。
本地安装
-安装之前需要配置好配置环境 找到php.exe 复制文件路径
配置环境变量
切换到国内镜像
有两种方式启用本镜像服务:
config.json
中。见“方法一”composer.json
文件中。见“方法二”打开命令行窗口(windows用户)或控制台(Linux、Mac 用户)并执行如下命令:
复制
composer config -g repo.packagist composer https://packagist.phpcomposer.com
在对应目录下运行cmd
composer create-project --prefer-dist laravel/laravel ./blog
composer create-project --prefer-dist laravel/laravel=5.4.* ./blog
首先,通过使用 Composer 安装 Laravel 安装器:
composer global require "laravel/installer"
确保将 composer vender bin 目录放置在你的系统环境变量 $PATH
中,以便系统可以找到 Laravel 的可执行文件。该目录根据您的操作系统存在不同的位置中;一些常见的配置包括:
$HOME/.composer/vendor/bin
$HOME/.config/composer/vendor/bin
安装完成后, laravel new
命令会在您指定的目录创建一个全新的 Laravel 项目。例如, laravel new blog
将会创建一个名为 blog
的目录,并已安装好所有的 Laravel 依赖项:
laravel new blog
storage\framework | 缓存 |
---|---|
php artisan server
<VirtualHost *:80>
DocumentRoot "D:\laravel\blog\public"
ServerName php.li
ServerAlias gohosts.com
<Directory "D:\laravel\blog\public">
Options FollowSymLinks ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
</VirtualHost>
配置后找到C:\Windows\System32\drivers\etc 下的 host 文件
-线上叫DNS域名解析
到最后添加
127.0.0.1 php.li
最后重启phpstudy
浏览器输入配置好的域名
// 请求方式为get 请求网站根路径
Route::get('/', function () {
// 显示试图页面 试图页面在项目 resources/views/下
return view('01');
});
Route::post($url,$callback);
Route::pust($url,$callback);
Route::patch($url,$callback);
Route::delete($url,$callback);
Route::options($url,$callback);
Route::match(['get','post'],'/',function(){
//
})
Router::any("/",function(){
//
})
必须参数
// 必填参数
Route::get('/{id}', function ($id) {
echo "id为".$id;
});
//选填参数 加个?号 不传默认为空 预付报错
Route::get('/home/{id?}', function ($id = "") {
echo "id为".$id;
});
127.0.0.1/home?id=111
的形式Route::get('/home', function () {
echo "id为".$_GET["id"];
});
name("别名")
Route::get('/home', function () {
echo "id为".$_GET["id"];
}) -> name("ABC");
查看所有路由
在项目下运行 cmd 收入
php artisan route:list
Route::group(['prefix' => "home"],function(){
Route::get("index",function(){
echo "匹配的是127.0.0.1/home/index";
});
Route::get("getUser",function(){
echo "匹配的是127.0.0.1/home/getUser";
});
Route::get("setMe",function(){
echo "匹配的是127.0.0.1/home/setMe";
});
});
目录: 项目目录/app/Http/Controllers
控制器命名规则: 首字母大写、驼峰命名法、最后加是controller.php
TextController.php
创建控制器
php artisan make:controller 控制器名 + controller
php artisan make:controlle TextContoller
//语法:Route::请求方式("路由表达式","控制器@方法名")
// "/home/test/show" --》 home下的test下的show方法
Route::get("/home/test/show","TextController@show");
php artisan make:controller Admin\IndexController
php artisan make:controller Home\IndexController
Route::get("/admin/index/index","Admin\IndexController@index");
Route::get("/home/index/index","Home\IndexController@index");
//引入 input
use Illuminate\Support\Facades\input;
Route::get('/Home',function(){
$a = input::get("id");
var_dump($a);
echo "
";
dd($a); //dd 相当于 var_dump 和 die() dd是Laravel中才有
});
input::all() 获取所有的get参数
//引入 input
use Illuminate\Support\Facades\input;
Route::get('/Home',function(){
$a = input::all("id");
var_dump($a);
echo "
";
dd($a); //dd 相当于 var_dump 和 die() dd是Laravel中才有
});
input::only([]);
获取指定的参数如: input::only(['id'])
input::except([])
获取指定的参数以外的所有参数input::has('name')
判断某个参数是否存在上面的方法既可以获取get的参数 也可以获取post 的参数
public function add(){
//获取要操作的数据表 插入一维数组
$text = DB::table("study") -> insert([
"name" => "小明",
"age" => 18,
"emily" => "[email protected]"
]);
//输出返回的结果
dd($text);
}
public function upDate(){
//获取数据表
$db = DB::table("study");
$text = $db -> where("id","=","1") -> update([
"name" => "大明"
]);
echo "返回结果为受影响的行数";
dd($text);
}
DB::table("study") -> where("id","=","1") -> update([])
DB::table("study") -> where()->where()->where()
DB::table("study") -> where()->orWhere()->oWhere()
get获取到的数据 是以对象的形式获取的 不是数组
public function select(){
$data = DB::table('study') ->get();
foreach($data as $key => $value) {
echo "id:{$value -> name},姓名:{$value-> age},邮箱:{$value -> emily}
";
}
dd($data);
}
public function select(){
$db = DB::table('study');
$data1 = $db -> where("id",">","2") -> where("age",">","18") -> first();
dd($dat11);
}
$date = DB::table("study") -> where("id","1") -> value("name");
$date = DB::table("study") -> where("id","1") -> select("name","age","emily") -> get();
//起别名
$date = DB::table("study") -> select("name as userName","age","emily") -> get();
$data = DB::table("study") ->orderBy('Id','desc')->get();
$data1 = DB::table("study") ->orderBy('age','asc')->get();
//重第二条开始数一条 包含第二条
$data1 = DB::table("study") ->limit(2)->offset(1)->get();
语法格式
@foreach ($data as $vkey => $value )
循环体
@endforeach
语法格式
@if(条件)
代码
@elseif(条件)
代码
@else
代码
@endif
编写父级模板
@yield('名字')
@extends('模板文件路径')
@section('名字')
html内容
@endsection
项目中两种方式都可以使用
上面的请求地址不同 Laravel防CSRF攻击 默认是开启的 会出现如下报错
VerifyCsrfToken.php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
//填写要排除的csrf校验 的路由
"/home/text/text1",
"/home/text/text2"
];
}
protected $except = [
//填写 * 排除所有的 csrf校验 的路由
"*"
];
创建语法
php artisan make:model 模型名称
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class IndexMode extends Model
{
//必选 定义模型关联的数据表 (一个模型通常只关联一个数据表)
protected $table = "study";
//定义主键 (可选)
protected $primaryKey = "Id";
// 定义禁止操作时间
public $timestamps = false;
//设置允许写入的数据字段
protected $fillable = ['Id','name','age','emily'];
}
$reques 语法 (获取用户提交参数的数据) 与input相类似
查询方法与DB 基本相同
$row = IndexHome::where("Id","3") -> delete();
//返回受影响的行数
dd($row);
public function text3(Request $Request){
if (input::method() == "POST"){
//配置规则
$this->validate($Request,[
//不能为空 |最小2个字|最大100个
'name' => 'required|min:2|max:8',
'age' => 'required|min:1|max:100',
'emily' => 'required|email'
]);
} else {
return view('/Home/goIndex');
}
}
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}li>
@endforeach
ul>
div>
@endif
<form action="" method="post">
<p>请输入姓名:<input type="text" name="name">p>
<p>请输入年龄:<input type="text" name="age">p>
<p>请输入邮箱:<input type="email" name="emily">p>
{{ csrf_field() }}
<p><input type="submit" value="提交"> p>
form>
网址:https://packagist.org/?query=laravel-lang
安装 composer require caouecs/laravel-lang:~3.0
指定版本
composer require caouecs/laravel-lang
不限定版本
// Symfony\Component\HttpFoundation\File\UploadedFile类
// 判断请求中是否包含name=file的上传文件
$file=$request->hasFile('file');
// 文件上传过程中是否出错
$file->isValid();
// 获取原来的名字
$file->getClientOriginalName();
// 扩展名
$file->getClientOriginalExtension();
// 临时绝对路径
$realpath=$file->getRealPath();
//mime类型
$file->getClientMimeType();
// 转移实例目录
$file->move($destPath,$filename);
// Illuminate\Support\Facahes\Storage
Storage::disk('uploads')->put($filename,file_get_contents($realpath))
//public路径
public_path('uploads');
文件目录操作
File::exists('path');
// 获取文件内容
File::getRequire('path');
/ 将内容写入文件
File::put('path', 'contents');
// 将内容添加在文件原内容后
File::append('path', 'data');
// 通过给定的路径来删除文件
File::delete('path');
// 将文件复制到新目录下
File::copy('path', 'target');
// 从文件的路径地址提取文件的扩展
File::extension('path');
// 获取文件类型
File::type('path');
// 获取文件大小
File::size('path');
// 获取一个目录下的所有文件, 以数组类型返回
File::files('directory');
// 递归式删除目录
File::deleteDirectory('directory', $preserve = false);
// 清空指定目录的所有文件和文件夹
File::cleanDirectory('directory');
view
<form action="" method="post" enctype="multipart/form-data">
<p>姓名:<input type="text" name="name" placeholder="请输入姓名">p>
<p>年龄:<input type="text" name="age" placeholder="请输入年龄">p>
<p>邮箱:<input type="emily" name="emily" placeholder="请输入邮箱">p>
<input type="file" name="sartar" />
{{ csrf_field() }}
<p><input type="submit" value="提交">p>
form>
路由 Route::any(’/home/text/text5’,‘TextController@text5’);
模型
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class IndexMode extends Model
{
//定义模型关联的数据表 (一个模型通常只关联一个数据表)
protected $table = "study";
//定义主键 (可选)
protected $primaryKey = "Id";
// 定义禁止操作时间
public $timestamps = false;
//设置允许写入的数据字段
protected $fillable = ['Id','name','age','emily','sartar'];
}
controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\input;
//引入模型
use App\Home\IndexMode;
class TextController extends Controller
{
public function text5(Request $Request){
if (input::method() == "POST"){
//获取数据 'name','age','emily'
$data = $Request -> only(['name','age','emily']);
$file = $Request->file('sartar');
// 此时 $this->upload如果成功就返回文件名不成功返回false
$fileName = $this->upload($file);
if ($fileName){
$data['sartar'] = $fileName ;
//保存到数据库
dd(IndexMode::create($data));
}
return '上传失败';
}
return view('/Home/text5');
}
public function upload($file, $disk='public') {
// 1.是否上传成功
if (! $file->isValid()) {
return false;
}
// 2.是否符合文件类型 getClientOriginalExtension 获得文件后缀名
$fileExtension = $file->getClientOriginalExtension();
if(! in_array($fileExtension, ['png', 'jpg', 'gif','jpeg'])) {
return "文件类型错误";
die();
}
// 3.判断大小是否符合 2M
$tmpFile = $file->getRealPath();
if (filesize($tmpFile) >= 2048000) {
return "文件过大";
die();
}
// 4.是否是通过http请求表单提交的文件
if (! is_uploaded_file($tmpFile)) {
return "提交错误";
die();
}
// 5.每天一个文件夹,分开存储, 生成一个随机文件名
$fileName = date('Y_m_d').'/'.md5(time()) .mt_rand(0,9999).'.'. $fileExtension;
$filePate = "/upload/".date('Y_m_d');
if ($file ->move($filePate,$fileName)){
//返回文件目录
return '/upload/'.$fileName;
}
}
}
public function text6(){
//数据模型::paginate(1) 一个页面一条数据
$data = IndexMode::paginate(1);
return view('Home/text6',compact('data'));
}
<table border="1">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>邮箱</td>
<td>头像</td>
</tr>
@foreach ($data as $value)
<tr>
<td>{{ $value -> name }}</td>
<td>{{ $value -> age }}</td>
<td>{{ $value -> emily }}</td>
<td><img src="{{ ltrim($value -> sartar,".") }}" width="50px" alt=""></td>
</tr>
@endforeach
</table>
//显示分页链接
{{ $data ->links() }}
#pull_right{
text-align:center;
}
.pull-right {
/*float: left!important;*/
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #428bca;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
color: #2a6496;
background-color: #eee;
border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 2;
color: #fff;
cursor: default;
background-color: #428bca;
border-color: #428bca;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd;
}
.clear{
clear: both;
}
https://packagist.org/?query=captcha
要求:
php: ^7.2
开启GD库
同时需要开启php_fileinfo.dll and php_mbstring.dll
安装 :
改镜像
composer config -g repo.packagist composer https://packagist.phpcomposer.com
cmd运行:composer require mews/captcha
修改配置文件:config/app.php
配置provider 信息
'providers' => [
// ...
Mews\Captcha\CaptchaServiceProvider::class,
]
配置别名
'aliases' => [
// ...
'Captcha' => Mews\Captcha\Facades\Captcha::class,
]
基本使用
如果需要自定义配置,则需要生成配置文件
cmd 项目根目录运行:php artisan vendor:publish
生成后目录:config/captcha.php
//表单的自动验证
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="" method="post">
<p>请输入姓名:<input type="text" name="name"></p>
<p>请输入年龄:<input type="text" name="age"></p>
<p>请输入邮箱:<input type="email" name="email"></p>
<p>请输入验证码:<input type="text" name="captcha"></p>
<!-- //验证码图片 -->
<img src="{{ captcha_src() }}" alt="">
{{ csrf_field() }}
<p><input type="submit" value="提交"> </p>
路由 Route::any(’/home/text/text3’,‘TextController@text3’);
public function text3(Request $Request){
if (input::method() == "POST"){
//配置校验规则
$this->validate($Request,[
//不能为空 |最小2个字|最大100个
'name' => 'required|min:2|max:8',
'age' => 'required|min:1|max:100',
'email' => 'required|email',
//captcha 校验验证码
'captcha' => 'required|captcha'
]);
} else {
return view('/Home/goIndex');
}
}
创建迁移文件语法:php artisan make:migration 迁移文件名
迁移文件无需目录管理
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePaperTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('paper', function (Blueprint $table) {
//自增的主键id
$table->increments('id');
//试卷名称,唯一,varchar(100),不能为空
$table -> string('paper_name','100') -> notNull() -> unique();
//试卷总分,整形数字,tinyint类型 不能空
$table - >tinyInteger('total_score') -> default(100);
//试卷开始考试时间 时间戳类型 (整型int)
$table -> integer('start_time') -> nullable();
//考试时间长度,单位分钟,整型tinyint
$table -> tinyInteger('duration');
//试卷是否启用状态1表示启用2表示禁用
$table -> tinyInteger('status')-> default(1);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
}
执行 php artisan migrate:install 会生成
执行 php artisan migrate
php artisan migrate:rollback
填充操作就是数据表写参数数据的操作 (增加操作)
php artisan make:seeder 填充器名称
【约定俗称的语法 大写表面+TableSeeder】
use Illuminate\Database\Seeder;
class PaperTableSeeder extends Seeder
{
public function run()
{
$data = [
[
'paper_name' => '五年高考,三年模拟',
'start_time' => strtotime('+7 days'),
'duration' => '120'
],
[
'paper_name' => '黄冈密卷',
'start_time' => strtotime('+7 days'),
'duration' => '120'
],
[
'paper_name' => 'XXX高中期中考试试卷',
'start_time' => strtotime('+7 days'),
'duration' => '120'
]
];
DB::table('paper') -> insert($data);
}
}
php artisan db:seed --class 需要执行的种子文件(不要.php)
填充器的执行操作没有回滚一说,没有删除,如果需要回滚,则可以手动亲空对应的数据表
<button id="btn">点击</button>
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
<script>
$(function($){
$('#btn').click(function (){
$.ajax({
url:'/home/text/text7_ajax',
type:'get',
dataType:'json',
success:function (res){
console.log(res);
}
})
})
})
</script>
public function text7(){
return view('Home/text7');
}
public function text7_ajax(){
$data = IndexMode::all();
// php 返回json数据
// return json_encode($data);
//laravel 框架 返回json数据
return response() -> json($data);
}
//session 会话控制
// use Session ....
public function text8(){
//设置Session
Session::put('name',"小明");
//获取Session
echo '获取session-》'.Session::get('name');
//获取session获取 如果没有返回默认值
echo "
";
echo '获取失败返回默认值-》'.Session::get('age','not session');
// echo Session::get('agee',function (){ return "没有";});
//
//删除
Session::forget('name');
}
//设置存储数据 name 有效期10分钟
Cache::put("name","小小明",10);
//获取
echo Cache::get("name");
//获取 如果不存在 返回默认值
echo "
";
echo Cache::get("name1","这家伙很懒,什么都没有留下");
//删除数据
Cache::forget("name");
//从缓存中获取数据然后删除
Cache::put("name2","获取后删除",10);
echo "
";
echo Cache::pull("name2");
//删除所有
Cache::flush();
//默认每次递增1
Cache::increment('key');
//每次递增10
Cache::increment('key',10);
//每次递减10;
Cache::decrement('key',10);
迁移文件 2019_12_01_071055_create_article_table.php
Schema::create('article',function(Blueprint $table){
$table -> increments("id");
$table -> string('article_name',100) -> notNull();
$table -> integer('author_id') -> notNull();
});
迁移文件 2019_12_01_071253_create_author_table.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAuthorTable extends Migration
{
public function up()
{
Schema::create('author',function(Blueprint $table){
$table -> increments("id");
$table -> string("author_name") -> notNull();
});
}
public function down()
{
Schema::dropIfExists('author');
}
};
填充器:authorAndAarticleTableSeeder.php
use Illuminate\Database\Seeder;
class authorAndAarticleTableSeeder extends Seeder
{
public function run()
{
DB::table('article')->insert([
[
'article_name' => '我有棒棒糖你要嘛',
'author_id' => rand(1,3)
],
[
'article_name' => '就是不给你',
'author_id' => rand(1,3)
],
[
'article_name' => '哈哈!骗你的',
'author_id' => rand(1,3)
]
]);
DB::table('author')->insert([
['author_name' => '新浪网'],
['author_name' => '和讯网'],
['author_name' => '网易']
]);
}
}
public function text10(){
// sql语句
//seclec t1.id,t1.article_name,t2.author_name from article as t1 left join author as t2 on ti.article_name = t2.id
//laravel leftJoin
$data = DB::table("article as t1") -> select("t1.id","t1.article_name","t2.author_name") -> leftJoin("author as t2","t1.author_id","=", "t2.id") -> get();
dd($data);
}
CreateArticleTable 迁移文件
public function up()
{
Schema::create('article',function(Blueprint $table){
$table -> increments("id");
$table -> string('article_name',100) -> notNull();
$table -> integer('author_id') -> notNull();
});
}
CreateAuthorTable 迁移文件
public function up()
{
Schema::create('author',function(Blueprint $table){
$table -> increments("id");
$table -> string("author_name") -> notNull();
});
}
authorAndAarticleTableSeeder 填充器
public function run()
{
DB::table('article')->insert([
[
'article_name' => '我有棒棒糖你要嘛',
'author_id' => rand(1,3)
],
[
'article_name' => '就是不给你',
'author_id' => rand(1,3)
],
[
'article_name' => '哈哈!骗你的',
'author_id' => rand(1,3)
]
]);
DB::table('author')->insert([
['author_name' => '新浪网'],
['author_name' => '和讯网'],
['author_name' => '网易']
]);
}
ArtcleMode 模型
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class ArtcleModeextends Model
{
protected $table = 'author';
}
AuthorMode 模型
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class AuthorMode extends Model
{
protected $table = 'author';
}
在ArtcleMode 模型中
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class ArtcleMode extends Model
{
protected $table = 'article';
//模型的关联操作 (一对一) 函数名为要关联的表模型的小写名
public function author(){
//hasOne('要关联的表模型空间地址','被关联模型的关系字段','本模型关联的关系字段')
return $this -> hasOne('App\Home\AuthorMode','id','author_id');
}
}
路由 /home/text/test21
CommentTable 迁移文件
public function up()
{
Schema::create('comment',function(Blueprint $table){
$table -> increments('id');
$table -> string('comment') -> notNull;
$table -> tinyInteger('article_id');
});
}
commentTableSeefer 填充器
use Illuminate\Database\Seeder;
class commentTableSeefer extends Seeder
{
public function run()
{
DB::table("comment") -> insert([
[
"comment" => "巴拉巴拉巴拉巴拉我是一条评论",
"article_id" => rand(1,3),
],
[
"comment" => "巴拉巴拉巴拉巴拉我是一坨评论",
"article_id" => rand(1,3),
],
[
"comment" => "巴拉巴拉巴拉巴拉我是一堆评论",
"article_id" => rand(1,3),
],
[
"comment" => "巴拉巴拉巴拉巴拉我是一行评论",
"article_id" => rand(1,3),
],
]);
}
}
CommentMode 表模型
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class CommentMode extends Model
{
protected $table = "comment";
}
在ArtcleMode 模型中
//模型的关联操作 (一对多
public function comment(){
//hasMany('要关联的表模型空间地址','被关联模型的关系字段','本模型关联的关系字段')
return $this -> hasMany('App\Home\CommentMode','article_id','id');
}
路由 /home/text/text12
//关联模型 一对d多
public function text12(){
$data = \App\Home\ArtcleMode::get();
foreach ($data as $key => $value){
echo "文章为:".$value -> article_name . "评论有:"."
";
//获取当前评论下的全部评论挨个输出
foreach($value -> comment as $k => $v){
echo " " . $v -> comment ."
";
}
}
}
CreateKeywordTable 迁移文件
CreateRelationTable 迁移文件
KeywordAndRelationSeeder 填充器
keywordMode 模型表
namespace App\Home;
use Illuminate\Database\Eloquent\Model;
class keywordMode extends Model
{
protected $table = "keyword";
}
在ArtcleMode 模型中
//模型的关联操作 (多对多
public function keyword(){
// belongToMany('被关联的表模型空间地址','多对多模型的关系表名','当模型中的关系键','被关联模型的关系键')
return $this->belongSToMany('App\Home\keywordMode','relation','article_id','key_id');
}
路由 /home/text/text13
//模型的关联操作 (多对多
public function keyword(){
// belongToMany('被关联的表模型空间地址','多对多模型的关系表名','当模型中的关系键','被关联模型的关系键')
return $this->belongSToMany('App\Home\keywordMode','relation','article_id','key_id');
}
packagist文档:https://packagist.org/packages/fzaninotto/faker
常用数据:https://www.cnblogs.com/hjcan/p/11551216.html
use Illuminate\Database\Seeder;
class managerTableSeeder extends Seeder
{
public function run()
{
//生成faker实例 zh_CN 设置为中文区域
$faker = \Faker\Factory::create('zh_CN');
//循环生成数据
$data = [];
for($i = 0; $i < 100; $i++){
$data[] = [
'username' => $faker -> name($gender = null|'male'|'female'), //生成用户名(姓名)
'password' => bcrypt('123456'), //生成用户名
'grender' => rand(1,3), //随机性别
'moblie' => $faker -> phoneNumber, //手机号
'email' => $faker -> email, //邮箱
'role_id' => rand(1,6), //角色ID
'created_at' => date("Y-m-d H:i:s",time()), //创建时间
'status' => rand(1,2) //账号状态
];
}
DB::table('manager') -> insert($data);
}
}
配置文件 在config/auth.php
数据表模型 文件
namespace App\Admin;
use Illuminate\Database\Eloquent\Model;
class Manager extends Model
{
protected $table = "manager";
}
//继续开始进行身份验证
$data = $Request -> only(['username','password']);
$data['status'] = '2'; //要求状态为启动的用户
//传递给 guard 方法的 guard 名称对应配置文件 auth.php 中 guards 配置的某个键|| $Request -> get('online') 保持登录状态
$result = Auth::guard('manager') -> attempt($data,$Request -> get('online'));
if ($result) {
return redirect('/admin/public/index');
} else {
return redirect('/admin/public/login') -> withErrors([ //返回错误信息给MessageBag 实例
"loginError" => "用户名或密码错误",
]);
}
//判断是否登录
if (Auth::guard('manager') -> check()) {
// 用户已登录...
}
// 获取当前已认证的用户...
$user = Auth::guard('manager') -> user();
// 获取当前已认证的用户 ID...
$id = Auth::guard('manager') -> id();
Datatables插件是一款基于jQuery框架进行开发的无刷新分页插件,其除了分页还有排序、搜索等功能。
官网:https://www.datatables.net/
该分页插件有2种形式:客户端分页方式、服务端分页方式(limit)