1. 項目創建
首先我們用composer創建項目 , composer會根據當前的php版本 幫我們選擇支持的最高版本
composer create-project --prefer-dist laravel/laravel myblog
laravel新版本比較激進 ,需要最低 php7 支持
2. 項目配置 數據庫配置 ,時區配置 ,路由配置等等
項目配置主要在根目錄下的 .env 文件中
主要是數據庫配置 ? 和 redis的配置?
//數據庫配置
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
//redis配置
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
注意 config / app.php 文件 ,改時區,一般默認是PRC
'timezone' => 'PRC',
3. 留言板增刪改查? ?
public function addsave(Request $request){$postdata = $request->all();//驗證數據$rules = ['title' => 'required|unique:dw_msg|max:100', /*此處規則為必須 標題唯一,驗證器會到dw_msg里找 最長長度為100個字符*/'content' => 'required|max:100',];$validator = Validator::make($postdata, $rules);if ($validator->fails()) {return redirect('error')->withErrors($validator)->withInput();}else{$u = json_decode(json_encode(Session::get('userinfo')[0]),true);$res = DB::insert('insert into dw_msg (title,content,uid,time) values (:title,:content,:uid,:time)', ['title'=>$postdata['title'],'content'=>$postdata['content'],'uid'=>$u['uid'],'time'=>time() ]);if($res){return redirect('/');}else{echo 'insert data fails';exit();}}}
這里主要介紹添加數據這個操作 。
這里使用到 ?接收參數的Request包 ? , 驗證數據的Validator包 ?和 數據庫DB包 ?和 會話控制包 Session ?,分別需要在頭部引入
use Illuminate\Http\Request; //默認導入的包
use Illuminate\Support\Facades\Validator;
use DB; //等同于 use Illuminate\Support\Facades\DB;
use Session;
可以看到類中大量導入 Illuminate\Support\Facades? ? 這個命名空間下的類 。
Facades 是 laravel 中比較核心的類庫 ,包括諸如 session ,DB,Route 等等底層類
4. 分頁
laravel中實現分頁也比較簡單
$results = DB::table('dw_msg')->orderBy('id','desc')->paginate(8);
return view('msg.index', ['list'=>$results]);
視圖頁碼顯示:
{{$list->links()}}
默認顯示樣式:
還有一種是 ?simplePaginate(15); ? ? 這種只顯示上一頁 和下一頁
5. 登錄模塊 和 session 的使用
$res = DB::select('select * from dw_user where username = :u', ['u' => $postData['username']]);
$tmp = json_decode(json_encode($res),true);
$md_for_pass = set_passwords($postData['password'],$tmp[0]['salt']);
if($tmp[0]['password']== $md_for_pass){Session::put('userinfo',$res);Session::save();echo 'login success';exit();
}else{echo 'login fail';exit();
}
對象轉換數組的方法:
$tmp = json_decode(json_encode($res),true);
一般DB類查詢數據 ,都會返回 ?stdclass 對象 ? ,可直接使用 ?,可轉換使用
6. 加入驗證碼
驗證碼使用composer引入第三方的類
composer require "gregwar/captcha 1.*"
控制器:
namespace App\Http\Controllers\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use Session;class codeController extends Controller
{public function captcha($temp){$builder = new CaptchaBuilder();$builder->build(100,32);$phrase = $builder->getPhrase();//把內容存入sessionSession::flash('milkcaptcha', $phrase); //存儲驗證碼ob_clean();return response($builder->output())->header('Content-type','image/jpeg');}}
視圖使用:
驗證碼:<img src="/getcode/1" alt="點擊刷新" onclick="this.src='/getcode/'+ Math.random();" style="cursor:pointer" align="absmiddle"/>
參考:laravel自帶驗證碼類的使用 - 程序員大本營
7. redis的使用
composer導入:
composer require predis/predis
首先需要引入
use Illuminate\Support\Facades\Redis;try{Redis::set('key','value123123');$value = Redis::get('key');echo $value;
}catch (\Exception $e){//返回服務器內部錯誤 500 的響應碼echo $e->getMessage();
}
8. model層的使用
namespace App;use Illuminate\Database\Eloquent\Model;class dw_msg extends Model
{//protected $table="dw_msg";protected $primaryKey = "id";protected $fillable = ['title', 'content', 'uid',];public $timestamps = false;
}
1.?protected $table="dw_msg" ? ??默認規則是模型類名的復數作為與其對應的表名,除非在模型類中明確指定了其它名稱?
??
2. protected $primaryKey = "id";??默認每張表的主鍵名為id ,你可以在模型類中定義一個$primaryKey 屬性來覆蓋該約定
3.?protected $fillable? ?用于調用create() ?方法時候 的白名單。 如圖定義了?'title', 'content', 'uid' 字段
4.?public $timestamps = false;??默認情況下,Eloquent 期望created_at 和updated_at 已經存在于數據表中,如果你不想要這些 Laravel自動管理的列,在模型類中設置$timestamps 屬性為false
常見的增刪改查方法,具體可查看線上手冊
//獲取所有記錄
$flights = Flight::all();// 獲取匹配查詢條件的第一個模型...
$flight = App\Flight::where('active', 1)->first();//插入數據
$flight = new Flight;
$flight->name = $request->name;
$flight->save();//更新數據
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();//刪除
$deletedRows = App\Flight::where('active', 0)->delete();
9.要注意的幾個問題
? ??? ??
? ? 9.1 ?公共函數如何添加
? ? 1.在app/Helper/下新建functions.php 文件?
? ? 2.?打開項目根目錄下的 composer.json 文件,找到"autoload" 配置項,補充如下代碼:
"files":["app/Helper/functions.php"]
? ??
? ?3. 在根目錄執行?
composer dump-auto