Laravel框架授課筆記
==============================================================
課程大綱:
1. composer的安裝
2. laravel框架的安裝
3. 本地域名解析與apapche虛擬主機配置
4. 環境配置與數據庫連接
目錄結構介紹
路由使用
控制器使用
5. laravel數據庫遷移工具
6. laravelDebug安裝與調試命令
一、 composer的安裝:
--------------------------------------------------------------
1.Composer是什么?
是 PHP 用來管理依賴(dependency)關系的工具。
你可以在自己的項目中聲明所依賴的外部工具庫(libraries),
Composer 會幫你安裝這些依賴的庫文件。
2.網址:https://getcomposer.org
下載:https://getcomposer.org/download/
中國全量鏡像:http://pkg.phpcomposer.com/
啟用本鏡像服務命令:
composer config -g repo.packagist composer https://packagist.phpcomposer.com
或
composer config repo.packagist composer https://packagist.phpcomposer.com
3.Composer常用命令:
composer -v 查看版本
composer selfupdate 更新composer
二、安裝Laravel框架
------------------------------------------------------------------
文檔網站:http://www.golaravel.com/
選擇5.1版本:http://www.golaravel.com/laravel/docs/5.1/
對運行環境的要求:
- PHP >= 5.5.9
- OpenSSL PHP 擴展
- PDO PHP 擴展
- Mbstring PHP 擴展
- Tokenizer PHP 擴展
通過 Composer Create-Project 命令安裝 Laravel:
命令:composer create-project laravel/laravel --prefer-dist
三、本地域名解析與apapche虛擬主機配置(window下)
------------------------------------------------------------------
1. 打開:C:\Windows\System32\drivers\etc目錄中的hosts文件:
配置信息:127.0.0.1 自定義主機名
2. 在apache的httpd-vhosts.conf配置文件中配置
<VirtualHost *:80>
ServerAdmin zhangtao@lampbrother.net
DocumentRoot "虛擬主機目錄位置"
ServerName 虛擬主機名
ErrorLog "logs/虛擬主機名-error.log"
CustomLog "logs/虛擬主機名-access.log" common
</VirtualHost>
Linux下的虛擬主機配置(ubuntu系統)
---------------------------------
1. 在hosts文件中配置域名解析到本地
# sudo vim /etc/hosts 文件
在里面添加一行代碼
127.0.0.1 blog.com
保存后執行命令讓他生效
# sudo resolvconf -u
測試:
# ping blog.com
2. 配置虛擬主機
復制一個虛擬主機配置文件
#sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/blog.conf
# sudo ln -s /etc/apache2/sites-available/blog.conf /etc/apache2/sites-enabled/
編輯 /etc/apache2/sites-available/blog.conf 文件
# sudo vim /etc/apache2/sites-available/blog.conf
設置:
<VirtualHost *:80>
ServerAdmin zhangtao@lampbrother.net
DocumentRoot "虛擬主機目錄位置"
ServerName 虛擬主機名
ErrorLog "logs/虛擬主機名-error.log"
CustomLog "logs/虛擬主機名-access.log" common
</VirtualHost>
最后重啟apache服務
# sudo service apache2 restart
3. 開啟Apache的重寫模式
(通過創建軟鏈接設置)
#sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/
進入apache主配置文件:
#sudo vim /etc/apache2/apache2.conf
在配置文件中添加代碼如下:
<Directory /var/www/html/虛擬主機目錄位置>
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
最后重啟apache服務
# sudo service apache2 restart
四、應用程序結構介紹:
-----------------------------------------------------------------------
詳見手冊中《系統架構》的應用程序結構
五、HTTP 路由
-----------------------------------------------------------------------
1. 基本路由:
Route::get('/', function()
{
return 'Hello World';
});
Route::post('foo/bar', function()
{
return 'Hello World';
});
Route::put('foo/bar', function()
{
//
});
Route::delete('foo/bar', function()
{
//
});
Route::match(['get', 'post'], '/', function() //多種請求注冊路由
{
return 'Hello World';
});
2. 路由參數
Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
六. 環境配置與數據庫連接
---------------------------------------------------------------------------
修改:項目下的.env文件
六、laravelDebug安裝與調試命令
--------------------------------------------------------------------------
網址:https://github.com/barryvdh/laravel-debugbar
安裝命令:composer require barryvdh/laravel-debugbar
進入:config/app.php文件
配置:
Barryvdh\Debugbar\ServiceProvider::class,
'Debugbar' => Barryvdh\Debugbar\Facade::class,
執行命令:php artisan vendor:publish --provider="Barryvdh\Debugbar\ServiceProvider"
七、控制器的創建
----------------------------------------------------------------------------
創建一個RESTful資源控制器
命令:php artisan make:controller StuController
命令:php artisan make:controller StuController --plain (不好用)
--plain表示創建一個空的控制器
控制器中代碼
//在控制器中查詢數據,並加載模板輸出
public function index()
{
$list = \DB::table('stu')->get();
return view('stu.index',["list"=>$list]);
//return view('stu.index', compact('list'));
}
在routes.php的路由文件中配置
Route::get('stu/index', 'StuController@index');
public function index()
{
//$list = \DB::table('stu')->get();
$list = \DB::table('stu')->paginate(5);
//return view('stu.index',['list'=>[]]);
return view('stu.index',["list"=>$list]);
//return view('stu.index', compact('list'));
}
public function create()
{
return view("stu.create");
}
public function store(Request $request)
{
//dd($request);
$input = $request->all();
unset($input['_token']);
$id = \DB::table('stu')->insertGetId($input);
return "添加成功!id號".$id;
}
public function update()
{
return "update";
}
public function show($id)
{
$stu = \DB::table('stu')->where("id","=",$id)->first();
dd($stu);
}
public function destroy($id)
{
return "delete".$id;
}
八、 Laravel 中Request請求對象的使用
-----------------------------------------------------------
1. 使用方式:
1.1 通過 Facade
在控制器中使用: use Request導入
在控制器的方法中獲取參數信息:$name = Request::input('name');
1.2 通過依賴注入
在控制器中使用:use Illuminate\Http\Request; 導入
在控制器的方法中使用參數注入request對象
public function store(Request $request)
{
$name = $request->input('name');
}
2. 取得輸入數據:
2.1 $name = Request::input('name'); 獲取請求參數name的值
2.2 $name = Request::input('name', 'Sally'); 獲取參數name的值,若沒有則使用Sally默認值
2.3 if (Request::has('name')){ ... } 判斷是否有此參數。
2.4 Request::all(); 獲取所有參數值
2.5 獲取部分參數值
$data = $request->only("name","id"); //獲取部分參數值
$data = $request->except("name"); //獲取指定外部分參數值
2.6 獲取數組中的值
九. Laravel中的響應:Response
--------------------------------------------------------
1. 基本響應
1.1 從路由返回字串
Route::get("/hh",function(){
return "Hello World!";
});
1.2 自定義響應:
在控制器中使用response: use Illuminate\Http\Response;
控制器方法中的代碼
$content="Hello Laravel!";
$status = 200;
$value = "text/html";
return (new Response($content, $status))->header('Content-Type', $value);
1.3 在響應送出視圖
return response()->view('hello')->header('Content-Type',"text/html");
1.4 附加 Cookies 到響應
return response($content)->withCookie(cookie('name', 'value'));
2. 重定向
2.1 return redirect('user/login');
十 視圖
---------------------------------------------------------
視圖被保存在 resources/views 文件夾內
實例創捷一個vv.php視圖文件
//在控制器的方法中加載視圖方式:
1. return view("vv"); //加載視圖
2. return view("vv",['name'=>"zhangsan","age"=>20]); //加載視圖,並攜帶參數
3. return view("vv")->with("name","lisi")->with("age",30); //通過with攜帶參數值
在視圖中如何輸出
<body>
<h2>Laravel框架視圖測試</h2>
姓名:<?php echo $name; ?> 年齡:<?php echo $age; ?>
</body>
十一 模板引擎:--Blade
---------------------------------------------------
Blade 模板后綴名都要命名為 .blade.php
模板導入css等文件可以使用{{asset(‘css/bootstrap.min.css’)}}
<link href="/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<center>
@include('stu.menu')
<h3>瀏覽學生信息</h3>
<table width="700" border="1">
<tr>
<th>學號</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
<th>班級</th>
<th>操作</th>
</tr>
@foreach ($list as $ob)
<tr>
<td>{{ $ob->id }}</td>
<td>{{ $ob->name }}</td>
<td>{{ $ob->sex }}</td>
<td>{{ $ob->age }}</td>
<td>{{ $ob->classid }}</td>
<td><a href="/stu/{{ $ob->id}}">查看</a></td>
</tr>
@endforeach
</table>
<br/>
{!! $list->render() !!}
</center>
十二、模板繼承
----------------------------------------------------------
1. 定義一個父模板 Blade 頁面布局
<!-- Stored in resources/views/layouts/master.blade.php -->
<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
</body>
</html>
2. 在視圖模板中使用 Blade 頁面布局
@extends('layouts.master')
@section('title', 'Page Title')
@section('sidebar')
@@parent
<p>This is appended to the master sidebar.</p>
@stop
@section('content')
<p>This is my body content.</p>
@stop
十三 數據遷移
--------------------------------------------------
1. 創建一個新的遷移:
命令:php artisan make:migration create_表名_table
就會在database/migrations目錄下產生一個遷移類文件
遷移類包含了兩個方法:up和down。
up方法用於新增表,列或者索引到數據庫,[運行遷移]
down方法就是up方法的反操作,[撤銷遷移]
如下代碼:news新聞表
public function up()
{
Schema::create('news', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->index();
$table->string('author',50);
$table->text('content');
$table->integer('addtime')->unsigned();
//$table->timestamps();
});
}
public function down()
{
Schema::drop('news');
}
2.運行遷移
命令:php artisan migrate
3.回滾遷移
命令:php artisan migrate:rollback 回滾最后一個遷移
命令:php artisan migrate:reset 回滾所有遷移
十四、數據填充
----------------------------------------------
1.要生成一個填充器:
可以通過Artisan命令make:seeder。所有框架生成的填充器都位於database/seeders目錄:
命令:php artisan make:seeder 表名TableSeeder
如:php artisan make:seeder NewsTableSeeder
一個填充器類默認只包含一個方法:run。當Artisan命令db:seed運行時該方法被調用。
run方法可以插入任何你想插入數據庫的數據。
如下代碼:news表
public function run()
{
\DB::table('news')->insert([
'title' => str_random(20),
'author' => 內容,
'content' => 內容,
'addtime' => time()+rand(0,100000),
]);
}
2. 運行填充:
php artisan db:seed //填充DatabaseSeeder器類
php artisan db:seed --class=UserTableSeeder //獨立的填充器類
php artisan migrate:refresh --seed //回滾並重新運行遷移
Model的定義使用
---------------------------------------------------------------------
1. 自定義模型:
命令:php artisan make:model Models/模型名
會在app目錄下新建一個Models目錄,並創建一個模型類
如:php artisan make:model Models/Stu
這樣就會在app目錄下生成一個Models目錄,並且在Models目錄下生成一個Stu模型類。
Laravel 中所有模型類繼承自Illuminate\Database\Eloquent\Model類。
代碼如下:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Stu extends Model
{
//設置表名
public $table = 'stu';
//設置主鍵
public $primaryKey = 'id';
//設置日期時間格式
public $dateFormat = 'U';
//批量賦值屬性
protected $guarded = ['name','sex','age','classid'];
}
2. 自定義Model類常用操作
Stu::all(); 獲取所有信息方法
Stu::where('id','<',3)->orderBy('id','desc')->get(); 獲取多個
Stu::where('id',1)->first(); 獲取單個模型
Stu::find(1); 獲取單個模型
Stu::where('id','>',0)->count(); 聚合查詢使用
Stu::where('id','>',0)->max('age');
添加:
$stu = new Stu;
$stu->name = 'xiaoli';
$stu->age = 22;
$stu->sex = "m";
$stu->classid = 'lamp110';
if($stu->save()){
echo '添加成功!';
}else{
echo '添加失敗!';
}
或者
$input = [
'name'=>'xiaoli',
'age'=>21,
'sex'=>'m',
'classid'=>'lamp118',
];
$stu = Stu::create($input);
$stu->save();
更新:
$stu = Stu::find(1);
$stu->name = 'xiaozhang';
if($stu->save()){
echo '更新成功!';
}else{
echo '更新失敗!';
}
或
$input = [
'name'=>'xiaoli',
'age'=>21,
'sex'=>'m',
'classid'=>'lamp118',
];
$stu = Stu::find(6);
$stu->update($input);
刪除:
$stu = Stu::find(5);
if($stu->delete()){
echo '刪除成功!';
}else{
echo '刪除失敗!';
}
十五、 數據搜索加分頁
-------------------------------------------------
1. 在控制器中分頁查詢數據(執行每10條數據一頁)
$users = DB::table('users')->paginate(10); //標准
或
$users = DB::table('users')->simplePaginate(10); //顯示簡單的「下一步」和「上一步」鏈接
return view('user.index', ['users' => $users]); //放置到視圖中
2. 在視圖模版中輸出分頁信息(導入bootstrap的css樣式就好看了)
{!! $users->render() !!}
{!! $list->appends($where)->render() !!} //維持where搜索條件
3. 其他自定義分頁相見手冊文檔。
十六、 文件上傳
--------------------------------------------------
//如下一個控制器中執行上傳方法代碼如下
public function doUpload(Request $request)
{
//判斷是否有上傳
if($request->hasFile("upload")){
//獲取上傳信息
$file = $request->file("upload");
//確認上傳的文件是否成功
if($file->isValid()){
//$picname = $file->getClientOriginalName(); //獲取上傳原文件名
$ext = $file->getClientOriginalExtension(); //獲取上傳文件名的后綴名
//執行移動上傳文件
$filename = time().rand(1000,9999).".".$ext;
$file->move("./upload/",$filename);
return response($filename); //輸出
exit();
}
}
}
十七、 自定義圖片等比縮放類的使用
---------------------------------------------------
1. 將事先定義好的Image.php類放置到App/Org/目錄下(其中Org自定義目錄).
在類中定義命名空間:namespace App\Org;
2. 在使用的控制類中引入當前類: use App\Org\Image;
具體使用:
//執行縮放
$img = new Image();
$img->open("./uploads/".$filename)->thumb(100,100)->save("./uploads/s_".$filename);
十八、 使用第三方圖片處理插件:intervention/image
-------------------------------------------------------
1. 安裝:使用Composer命令,需要在你的Laravel框架目錄下執行如下命令執行安裝
$ php composer.phar require intervention/image
或 composer require intervention/image
2. 添加配置
修改/config/app.php配置文件
在$providers屬性中添加: Intervention\Image\ImageServiceProvider::class,
在$aliases屬性中添加:'Image' => Intervention\Image\Facades\Image::class,
3. 執行命令讓當前Laravel使用當前插件(原使用的是GD庫)
$ php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"
4. 測試: 在當前項目控制器中就可以使用下面代碼測試
use Intervention\Image\ImageManagerStatic as Image;
$img = Image::make("./uploads/".$filename)->resize(100,100);
$img->save("./uploads/s_".$filename); //另存為
return $img->response("jpg"); //輸出
//執行等比縮放
$img->resize(null, 400, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
十九、 表單驗證
------------------------------------------------------------------------------------
一、表單驗證:
1. 控制器驗證:
public function store(Request $request)
{
//驗證
$this->validate($request, [
'name' => 'required|max:255',
'age' => 'required|numeric|max:100|min:10',
]);
...
}
2. 在表單頁上顯示:
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul style="color:red;">
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
二十、在Laravel框架中使用驗證碼擴展(gregwar/captcha)
--------------------------------------------
首先呢在laravel5中默認是沒有提供驗證碼的,這里我們需要使用第三方提供的庫:gregwar/captcha
通過composer安裝:
在composer.json的require中加入"gregwar/captcha": "dev-master",具體代碼如下
"require": {
"laravel/framework": "5.0.*",
"gregwar/captcha": "1.*"
},
然后運行:# composer update命令
使用gregwar/captcha庫
使用就非常簡單了,直接上代碼
記得在頂部use Gregwar\Captcha\CaptchaBuilder;
function captch(){
$builder = new CaptchaBuilder;
$builder->build(150,32);
//Session::set('phrase',$builder->getPhrase()); //存儲驗證碼
return response($builder->output())->header('Content-type','image/jpeg');
}
在視圖中調用
<img src="{{ url('你定義的captch函數的路由') }}" >
驗證就更簡單了
function index(){
$yanzhengma = Session::get('phrase');
if($_POST['yanzhengma'] == $yanzhengma){
echo 'success';//驗證成功
}
}
記得別忘了在頂部use Session
還有 驗證碼需要你的環境安裝gd庫,要不然不會正常顯示
在 Laravel 中使用 SMTP 發送郵件
-------------------------------------------
1. 配置:
修改郵件發送配置。4.2 在 app/config/mail.php,5 在 config/mail.php,修改以下配置:
'host' => 'smtp.163.com',
'port' => 25,
'from' => array('address' => '***@163.com', 'name' => 'TestMail'),
'username' => '***@163.com', // 注意,這里必須和上一行配置里面的郵件地址一致
'password' => '****',
2. 發送:
在控制器或者模型里,調用以下代碼:
$data = ['email'=>$email, 'name'=>$name, 'uid'=>$uid, 'activationcode'=>$code];
Mail::send('activemail', $data, function($message) use($data)
{
$message->to($data['email'], $data['name'])->subject('歡迎注冊我們的網站,請激活您的賬號!');
});
Laravel框架中配置文件
-------------------------------------------
文件的文件夾
/app/config/
配置應用程序的運行時規則、 數據庫、 session等等。包含大量的用來更改框架的各個方面的配置文件。
大部分的配置文件中返回的選項關聯PHP數組。
/app/config/app.php
各種應用程序級設置,即時區、 區域設置(語言環境)、 調試模式和獨特的加密密鑰。
/app/config/auth.php 控制在應用程序中如何進行身份驗證,即身份驗證驅動程序。
/app/config/cache.php 如果應用程序利用緩存來加快響應時間,要在此配置該功能。
/app/config/compile.php
在此處可以指定一些額外類,去包含由‘artisan optimize’命令聲稱的編譯文件。
這些應該是被包括在基本上每個請求到應用程序中的類。
/app/config/database.php 包含數據庫的相關配置信息,即默認數據庫引擎和連接信息。
/app/config/mail.php 為電子郵件發件引擎的配置文件,即 SMTP 服務器,From:標頭
/app/config/session.php
控制Laravel怎樣管理用戶sessions,即session driver, session lifetime。
/app/config/view.php 模板系統的雜項配置。
其他目錄結構介紹:
-----------------------------------------
/app/controllers--包含用於提供基本的邏輯、 數據模型交互以及加載應用程序的視圖文件的控制器類。
/app/database/migrations/
包含一些 PHP 類,允許 Laravel更新當前數據庫的架構並同時保持所有版本的數據庫的同步。
遷移文件是使用Artisan工具生成的。
/app/database/seeds/--包含允許Artisan工具用關系數據來填充數據庫表的 PHP 文件。
/app/lang/
PHP文件,其中包含使應用程序易於本地化的字符串的數組。默認情況下目錄包含英語語言的分頁和表單驗證的語言行。
/app/models/
模型是代表應用程序的信息(數據)和操作數據的規則的一些類。在大多數情況下,
數據庫中的每個表將對應應用中的一個模型。應用程序業務邏輯的大部分將集中在模型中。
/app/start/
包含與Artisan工具以及全球和本地上下文相關的自定義設置。
/app/storage/
該目錄存儲Laravel各種服務的臨時文件,如session, cache, compiled view templates。
這個目錄在web服務器上必須是可以寫入的。該目錄由Laravel維護,我們可以不關心。
/app/tests/
該文件夾給你提供了一個方便的位置,用來做單元測試。如果你使用PHPUnit,
你可以使用Artisan工具一次執行所有的測試。
/app/views/
該文件夾包含了控制器或者路由使用的HTML模版。請注意,這個文件夾下你只能放置模版文件。
其他的靜態資源文件如css, javascript和images文件應該放在/public文件夾下。
/app/routes.php
這是您的應用程序的路由文件,其中包含路由規則,告訴 Laravel 如何將傳入的請求連接到路由處理的閉包函數、 控制器和操作。該文件還包含幾個事件聲明,包括錯誤頁的,可以用於定義視圖的composers。
/app/filters.php
此文件包含各種應用程序和路由篩選方法,用來改變您的應用程序的結果。Laravel 具有訪問控制和 XSS 保護的一些預定義篩選器。
Laravel中的數據導出--插件Laravel Excel
-------------------------------------------------------
在github上的地址: https://github.com/Maatwebsite/Laravel-Excel
官網:http://www.maatwebsite.nl/laravel-excel/docs
1. 安裝:
在laravel框架的composer.json文件的"require-dev"屬性中添加:
"maatwebsite/excel": "~2.1.0"
在命令行下運行: composer update命令進行更新
顯示效果:
.....
- Installing phpoffice/phpexcel (1.8.1)
Downloading: 100%
- Installing maatwebsite/excel (v2.1.2)
Downloading: 100%
.....
2. 配置:
在項目的config/app.php文件中添加設置:
2.1: 在'providers'中添加:
Maatwebsite\Excel\ExcelServiceProvider::class,
2.2: 在'aliases'中添加:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
2.3: 在命令行下運行: php artisan vendor:publish
C:\xampp\htdocs\lamp138_C\myobject>php artisan vendor:publish
Copied File [\vendor\maatwebsite\excel\src\config\excel.php] To [\config\excel.php]
Publishing complete for tag []!
3, 開發:
在控制器中:
public function excel()
{
\Excel::create('學生信息表', function($excel) {
$excel->sheet('基本信息', function($sheet) {
$sheet->row(1,['學號','姓名','性別','年齡','班級']);
$sheet->row(2,['1001','張三','男','22','lamp123']);
$sheet->row(3,['1002','李四','女','20','lamp138']);
});
})->export('xls');
}