安裝方法一:homestead 虛擬機php
安裝方法二:composer安裝
環境要求css
PHP >= 7.1.3 OpenSSL PHP Extension PDO PHP Extension Mbstring PHP Extension Tokenizer PHP Extension XML PHP Extension Ctype PHP Extension JSON PHP Extension
其次:composer安裝框架html
laravel new xxxproject
composer create-project --prefer-dist laravel/laravel xxxproject
location / { try_files $uri $uri/ /index.php?$query_string; }
目錄介紹:mysql
app //應用目錄 代碼基本都在這裏寫 bootstrap //框架啓動文件 路由緩存目錄 config //框架的配置目錄 database //數據庫目錄 數據遷移以及種子 public //框架入口文件 以及靜態文件 resources //資源目錄 視圖文件未編譯的jscss routes //路由目錄 storage //存儲目錄 編譯模板 日誌等。。 tests //測試文件 vendor //composer依賴包 .env //環境配置文件 artisan //命令行使用文件
基本路由 Route:構建最基本的路由只須要一個 URI 與一個 閉包Route::get('foo', function () {});
nginx
Route::get('/user', 'UserController@index');
Route::match(['get', 'post'], '/', $callback); Route::any('foo', $callback);
<form method="POST" action="/profile"> @csrf //或 {{ csrf_field() }} {{ method_field(方法名)}} </form>
取消csrf保護:app/Http/Middleware/VerifyCsrfToken.phpprotected $except = ['your/route'];
laravel
Route::redirect('/here', '/there', 301);
Route::view('/welcome', 'welcome', ['name' => 'Taylor']);
路由參數:web
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {});
Route::get('user/{nane?}',function($name='123'){});
Route::get('user/{ids?}',function($ids){ return $ids; })->where(‘ids’,‘[a-z]+’); //多個參數過濾 後面加數組
public function boot(){ Route::pattern('id', '[0-9]+'); parent::boot(); }
一旦定義好以後,便會自動應用這些規則到全部使用該參數名稱的路由上正則表達式
路由命名:
路由指定了名稱後,就可使用全局輔助函數 route 來生成連接或者重定向到該路由:sql
Route::get('user/{id}/profile', function ($id) {})->name('profile'); $url = route('profile', ['id' => 1]);// 生成 URL... return redirect()->route('profile'); // 生成重定向...
/** *處理一次請求。 *@param \Illuminate\Http\Request $request *@param \Closure $next *@return mixed */ public function handle($request, Closure $next){ if ($request->route()->named('profile')) {} return $next($request); }
Route::middleware(['first', 'second'])->group(function () { // 一下兩個路由均使用 first 和 second 中間件 Route::get('/', function () {}); Route::get('user/profile', function () {}); });
Route::namespace('Admin')->group(function () { // 在 "App\Http\Controllers\Admin" 命名空間下的控制器 });
請記住,默認狀況下,RouteServiceProvider 會在命名空間組中引入你的路由文件,讓你不用指定完整的 App\Http\Controllers 命名空間前綴就能註冊控制器路由。所以,你只須要指定命名空間 App\Http\Controllers 以後的部分。數據庫
Route::domain('{account}.myapp.com')->group(function () { Route::get('user/{id}', function ($account, $id) {}); });
Route::prefix('admin')->group(function () { // 匹配包含 "/admin/users" 的 URL Route::get('users', function () {}); });
Route::name('admin.')->group(function () { // Route assigned name "admin.users"... Route::get('users', function () {})->name('users'); });
Route::get('api/users/{user}', function (App\User $user) { return $user->email; });
/** *獲取該模型的路由的自定義鍵名。 *@return string */ public function getRouteKeyName(){ return 'slug'; }
public function boot(){ parent::boot(); Route::model('user', App\User::class); }
接着,定義一個包含 {user} 參數的路由:
Route::get('profile/{user}', function (App\User $user) {});
Route::fallback(function () {});
Route::middleware('auth:api', 'throttle:60,1')->group(function () { Route::get('/user', function () {}); });
Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () { Route::get('/user', function () {}); });
<form action="/foo/bar" method="POST"> <input type="hidden" name="_method" value="PUT"> <input type="hidden" name="_token" value="{{ csrf_token()}}"> </form> //你也可使用 @ method Blade 指令生成 _method 輸入: <form action="/foo/bar" method="POST"> @method('PUT') @csrf </form>
訪問當前路由
你可使用 Route Facade 上的 current、currentRouteName 和 currentRouteAction 方法來訪問處理傳入請求的路由的信息:
$route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();
若是你想知道全部可訪問的方法,能夠查看 API 文檔,瞭解 Route facade and Route 實例 的基礎類。
php artisan route:cache
php artisan route:clear
基礎控制器
須要着重指出的是,在定義控制器路由時咱們不須要指定完整的控制器命名空間。由於 RouteServiceProvider會在一個包含命名空間的路由器組中加載路由文件,因此咱們只需指定類名中 App\Http\Controllers 命名空間以後的部分就能夠了
class ShowProfile extends Controller{ /** *展現給定用戶的資料 *@param int $id *@return Response */ public function __invoke($id){ return view('user.profile', ['user' => User::findOrFail($id)]); } }
定義路由:Route::get('user/{id}', 'ShowProfile');
你能夠經過 Artisan 命令工具裏的make:controller命令中的--invokable 選項來生成一個可調用的控制器:php artisan make:controller ShowProfile --invokable
控制器中間件
Route::get('profile', 'UserController@show')->middleware('auth');
class UserController extends Controller{ /** *實例化一個控制器實例 *@return void */ public function __construct(){ $this->middleware('auth'); $this->middleware('log')->only('index'); $this->middleware('subscribed')->except('store'); } }
$this->middleware(function ($request, $next) { return $next($request); });
php artisan make:controller PhotoController --resource
Route::resource('photos', 'PhotoController');
Route::resources([ 'photos' => 'PhotoController', 'posts' => 'PostController' ]);
php artisan make:controller PhotoController --resource --model=Photo
Route::resource('photos', 'PhotoController')->only([ 'index', 'show' ]); Route::resource('photos', 'PhotoController')->except([ 'create', 'store', 'update', 'destroy' ]);
php artisan make:controller API/PhotoController --api
Route::resource('photos', 'PhotoController')->names([ 'create' => 'photos.build' ]);
Route::resource('users', 'AdminUserController')->parameters(['users' => 'admin_user']);
上例將會爲資源的 show 路由生成以下的 URI :/users/{admin_user}
use Illuminate\Support\Facades\Route; /** *初始化任何應用服務 *@return void */ public function boot(){ Route::resourceVerbs([ 'create' => 'crear', 'edit' => 'editar', ]); }
一旦動做被自定義後,像 Route::resource('fotos', 'PhotoController') 這樣註冊的資源路由將會產生以下的 URI:
/fotos/crear /fotos/{foto}/editar
Route::get('photos/popular', 'PhotoController@method'); Route::resource('photos', 'PhotoController');
<?php namespace App\Http\Controllers; use App\Repositories\UserRepository; class UserController extends Controller{ /** *用戶 repository 實例 ??? */ protected $users; /** *建立一個新的控制器實例 *@param UserRepository $users *@return void */ public function __construct(UserRepository $users){ $this->users = $users; } }
固然,你能夠輸入任何的 Laravel 契約 類型提示。 只要容器能夠解析它。根據你的應用,注入你的類型提示到控制器會提供更好可測試性。
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller{ /** *保存新用戶 *@param Request $request *@return Response */ public function store(Request $request){ $name = $request->name; } }
use Illuminate\Http\Request; Route::get('/', function (Request $request) {});
ip() 獲取訪問者ip 地址 // dd() 打印數據 並退出 userAgent() 獲取訪問者代理 route() 獲取路由請求的詳情 header() 獲取請求頭信息 url() 獲取請求地址 不包括查詢字符串 fullUrl() 獲取請求地址 包括查詢字符串 path() 獲取請求路徑 is() 方法能夠驗證傳入的請求路徑和指定規則是否匹配。 method() 獲取請求的方法 isMethod(方法名) 判斷請求方法 merge(數組) 合併新的數據到請求數據中 replace(數組) 替換請求數據 keys() 獲取全部的name has(name) 判斷是否傳過來值,當提供一個數組做爲參數時,has 方法將肯定是否存在數組中全部給定的值: filled('name') //肯定請求中是否存在值而且不爲空 file() 獲取文件的信息 all() 獲取全部發送的數據 input(name,默認值) 獲取get/post發送的數據 //不帶參數 獲取全部 query(name,默認值) 從查詢字符串獲取輸入 不加任何參數 獲取全部的 only(數組) 獲取指定的name except(數組) 不獲取指定的name
$name = $request->name;
$username = $request->old('username');
<input type="text" name="username" value="{{ old('username') }}">
$request->session()->put('key', 'value’); //存 $request->session()->get('key', 'default’); //取 $request->session()->has('users’); //判斷 $request->session()->forget('key') && $request->session()->flush();//刪除 flash(); //將輸入閃存至 Session flashOnly(); //將輸入閃存至 Session flashExcept();//將輸入閃存至 Session return redirect('form')->withInput( $request->except('password') );//把輸入閃存到 session 而後重定向到上一頁,這時只須要在重定向方法後加上 withInput 便可
$request->cookie('name');
或使用 Cookie Facade 來訪問 cookie 的值: $value = Cookie::get('name');
()response('Hello World')->cookie('name', 'value', $minutes[, $path, $domain, $secure, $httpOnly]);
Cookie::queue(Cookie::make('name', 'value', $minutes)); Cookie::queue('name', 'value', $minutes);
$cookie = cookie('name', 'value', $minutes); return response('Hello World')->cookie($cookie);
file() ;//獲取上傳文件,該file方法返回一個Illuminate\Http\UploadedFile類的實例,該類繼承了PHP的SplFileInfo 類的同時也提供了各類與文件交互的方法: hasFile() //確認請求中是否存在文件: isValid() /驗證上傳的文件是否有效: $request->photo->path(); //文件路徑 $request->photo->extension();//根據文件內容判斷文件的實際擴展名 //其它文件方法:UploadedFile 實例上還有許多可用的方法,能夠查看該類的 API 文檔 瞭解這些方法的詳細信息。 //存儲上傳文件 $request->photo->store('images'[, 's3']);//第二個參數,用於存儲文件的磁盤名稱。這個方法會返回相對於磁盤根目錄的文件路徑;` $request->photo->storeAs('images', 'filename.jpg'[, 's3']);//若是你不想自動生成文件名,那麼可使用 storeAs 方法,它接受路徑、文件名和磁盤名做爲其參數:
return response($content) ->header('Content-Type', $type) ->header('X-Header-One', 'Header Value') ->header('X-Header-Two', 'Header Value'); //或者,你可使用 withHeaders 方法來指定要添加到響應的頭信息數組: return response($content) ->withHeaders([ 'Content-Type' => $type, 'X-Header-One' => 'Header Value', 'X-Header-Two' => 'Header Value']);
return response($content) ->header('Content-Type', $type) ->cookie($name, $value, $minutes[, $path, $domain, $secure, $httpOnly]) //或者,使用 Cookie facade 「隊列」, Cookie 以附加到應用程序的傳出響應。 queue 方法接受一個 Cookie 實例或建立 Cookie 實例所需的參數。 這些 cookie 在發送到瀏覽器以前會附加到傳出響應中: Cookie::queue(Cookie::make('name', 'value', $minutes)); Cookie::queue('name', 'value', $minutes);
/** *設置不加密的 Cookie 名稱,數組形式 *@var array */ protected $except = [ 'cookie_name', ];
back()->withInput() //重定向到以前位置 redirect()->route('profile', ['id' => 1]) //重定向至命名路由 redirect()->action('UserController@profile', ['id' => 1]); //重定向至控制器行爲 redirect()->away('https://www.google.com'); //重定向到外部域 redirect('dashboard')->with('status', 'Profile updated!');重定向並使用with方法將數據閃存在 Session 中, redirect()->route('profile', [$user]); //經過 Eloquent 模型填充參數
若是要自定義路由參數中的值,那麼應該覆蓋 Eloquent 模型裏面的 getRouteKey 方法:
/** *獲取模型的路由鍵 *@return mixed */ public function getRouteKey(){ return $this->slug; }
return response() ->view('hello', $data, 200) ->header('Content-Type', $type);
return response() ->json(['name' => 'Abigail', 'state' => 'CA']) [->withCallback($request->input('callback'))];
return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers);//download 方法的第二個參數接受一個文件名,它將做爲用戶下載的時所看見的文件名。最後,你能夠傳遞一個 HTTP 響應頭數組做爲該方法的第三個參數 return response()->download($pathToFile)->deleteFileAfterSend(true);
管理文件下載的擴展包 Symfony HttpFoundation,要求下載文件名必須是 ASCII 編碼的。
return response()->file($pathToFile[, $headers]);//此方法接受文件的路徑做爲其第一個參數和頭信息數組做爲其第二個參數:
引入 Cookie :use Illuminate\Support\Facades\Cookie;
// 寫入 cookie $cookie = Cookie::make($key,$value,$minutest); //建立一個cookie實例 Cookie::queue($cookie ); //將新的實例加入到隊列 // 獲取 cookie Cookie::get($key) // 刪除 cookie $user = Cookie::forget('username'); Cookie::queue($user); //將新的實例加入到隊列 // 判斷 cookie 是否存在 Cookie::has('username');
默認狀況下,Laravel 生成的全部 Cookie 都是通過加密和簽名,所以不能被客戶端修改或讀取。 若是你想要應用程序生成的部分 Cookie 不被加密,那麼可使用在 app/Http/Middleware 目錄中 App\Http\Middleware\EncryptCookies 中間件的 $except 屬性:
protected $except = [ 'cookie_name', ];
助手函數
cookie([‘ag’=>33]); // 存儲,必須傳數組形式 cookie('ag’); // 獲取
引入 use Illuminate\Support\Facades\Session;
// 存儲 session Session::put(‘name’,‘liudehua’); //裏面也能夠用數組形式 // 獲取 Session::get(‘name’) // 刪除 Session::forget('name’); // 清空全部session Session::flush(); // 判斷是否存在session Session::has('key1’)
助手函數
session([‘ag’=>33]); // 存儲,必須傳數組形式 session('ag’); // 獲取
Blade 是 Laravel 提供的一個簡單而又強大的模板引擎。和其餘流行的 PHP 模板引擎不一樣,Blade 並不限制你在視圖中使用原生 PHP 代碼。全部 Blade 視圖文件都將被編譯成原生的 PHP 代碼並緩存起來,除非它被修改,不然不會從新編譯,這就意味着 Blade 基本上不會給你的應用增長任何負擔。
use Illuminate\Support\Facades\View; if (View::exists('emails.customer')) {}
return view()->first(['custom.admin', 'admin'], $data);
use Illuminate\Support\Facades\View; return View::first(['custom.admin', 'admin'], $data);
與全部視圖共享數據
若是須要共享一段數據給應用程序的全部視圖,你能夠在服務提供器的 boot 方法中調用視圖 Facade 的 share 方法。例如,能夠將它們添加到 AppServiceProvider 或者爲它們生成一個單獨的服務提供器:
<?php namespace App\Providers; use Illuminate\Support\Facades\View; class AppServiceProvider extends ServiceProvider{ /** *引導任何應用程序服務。 *@return void */ public function boot(){ View::share('key', 'value'); } /** *註冊服務提供商。 *@return void */ public function register(){} }
視圖合成器
視圖合成器是在渲染視圖時調用的回調或者類方法。若是你每次渲染視圖時都要綁定視圖的數據,視圖合成器能夠幫你將這些邏輯整理到特定的位置。
<?php namespace App\Providers; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider; //在下面這個例子中,咱們會在一個 服務提供商 中註冊視圖合成器,使用 View Facade 來訪問底層的 Illuminate\Contracts\View\Factory 契約實現。默認狀況下,Laravel 沒有存放視圖合成器的目錄,你須要根據需求來從新創建目錄,例如:App\Http\ViewComposers class ComposerServiceProvider extends ServiceProvider{ /** *在容器中註冊綁定。 *@return void */ public function boot(){ // 使用基於類的 composer... View::composer( 'profile', 'App\Http\ViewComposers\ProfileComposer' ); // 使用基於閉包的 composers... View::composer('dashboard', function ($view) {}); } /** *註冊服務器提供者。 *@return void */ public function register(){} }
注意,若是你建立了新的一個服務提供器來存放你註冊視圖合成器的代碼,那麼你須要將這個服務提供器添加到配置文件 config/app.php 的 providers 數組中。
到此咱們已經註冊了視圖合成器,每次渲染 profile 視圖時都會執行 ProfileComposer@compose 方法。那麼下面咱們來定義視圖合成器的這個類吧:
<?php namespace App\Http\ViewComposers; use Illuminate\View\View; use App\Repositories\UserRepository; class ProfileComposer{ /** *用戶 repository 實現。 *@var UserRepository */ protected $users; /** *建立一個新的 profile composer。 *@param UserRepository $users *@return void */ public function __construct(UserRepository $users){ // 依賴關係由服務容器自動解析... $this->users = $users; } /** *將數據綁定到視圖。 *@param View $view *@return void */ public function compose(View $view){ $view->with('count', $this->users->count()); } }
視圖合成器的 compose方法會在視圖渲染以前被調用,並傳入一個 Illuminate\View\View 實例。你可使用 with 方法將數據綁定到視圖。
View::composer( ['profile', 'dashboard'], 'App\Http\ViewComposers\MyViewComposer' );
composer 方法同時也接受通配符 ,表示將一個視圖合成器添加到全部視圖:
`View::composer('', function ($view) {});`
View::creator('profile', 'App\Http\ViewCreators\ProfileCreator');
流程控制
if語句: @if-@elseif-@else-@endif 指令構建 isset: @isset-@endisset `<p>{{ $name or ‘default’ }}</p> //短語法` switch: @switch、@case、@break、@default 和 @endswitch for循環 :@for-@endfor, @continue($i==5),@break($i==7) foreach 循環:@foreach-@endforeach $loop 變量 純PHP代碼: @php-@endphp
$loop 變量
@section 命令定義了視圖的一部份內容 @show @extends @yield('content') 用來顯示指定部分的內容。
例1:master.blade.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8" > <title> @yield('title') </title> <head> <body> @section('left') 這是left側邊欄。 @show @section('right') 這是right的側邊欄。 @show <div> @yield('content') </div> </body> </html>
例2:index.blade.php
@extends('layout.master') @section('title','這是個首頁') @section('left’) @parent 我是左邊的 @endsection @section('right') 我是右邊的 @endsection @section('content') <p>第一篇文章</p> <p>第二篇文章</p> @endsection
@include('layout.header’);
視圖數據共享
app/Providers/AppServiceProvider.php boot方法 use Illuminate\Support\Facades\View; View::share('username','liudehua');
<script src="/js/jQuery.min.js"></script>
Laravel 能使用原生 SQL、查詢構造器 和 Eloquent ORM 對數據庫進行操做
目前laravel支持 下面4種數據庫:MySQL/Postgres/SQLiteSQL/Server
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=test DB_USERNAME=root DB_PASSWORD=123456 'charset' => 'utf8', 'collation' => 'utf8_general_ci',
use Illuminate\Support\Facades\DB;
// 插入數據 返回 true 或者false DB::insert('insert into test (name,age) values (?,?)',['liming',23]); // 更新數據 返回影響的行數 DB::update('update test set age=? where id=?',[55,1]); // 查詢 數據返回一個數組,數組中的每一個結果都是一個 StdClass 對象 DB::select('select name,age from test where id=?',[2]); // 刪除 返回影響的行數 DB::delete('delete from test where id=?',[1]);
//1. 插入 //table 方法爲給定的表返回一個查詢構造器實例 DB::table('test')->insert(['name'=>'liudehua']); //插入一條數據,返回true、false DB::table('test')->insertGetId(['name'=>'liudehua']);//獲取插入數據的id 批量插入二維數組ååååå //2. 更新數據 $res = DB::åtable('test')->where('id',5)->update(['age'=>33]); //多條件 $res = DB::table('test')->where(['id'=>7,'name'=>'liudehua'])->update(['age'=>33]); $res = DB::table('test')->where('id','>',5)->update(['age'=>99]); //自增 默認爲自增 1 $res = DB::table('test')->where('id',4)->increment('age’); //自增 3 $res = DB::table('test')->where('id',4)->increment('age',3); //自減 默認爲 1 $res = DB::table('test')->where('id',4)->decrement(‘age’); //自減 3 $res = DB::table('test')->where('id',4)->decrement('age',3); //3. 刪除 $res = DB::table('test')->where('id',5)->delete(); //4. 獲取數據 :toArray() ,結果集轉數組 $res = DB::table('test')->get();//獲取多條數據 //獲取一條數據 不加條件默認獲取 第一條 $res = DB::table('test')->first(); //獲取某個字段的值 $res = DB::table('test')->where('id',3)->value('age’); //獲取一列的值 $res = DB::table('test')->pluck('age’); //獲取指定字段的值 $res = DB::table('test')->select('name','age')->get(); //5. 聚合函數: count, max, min, avg, 和 sum $res = DB::table('test')->sum('age’); $res = DB::table('test')->avg('age’); $res = DB::table('test')->min('age’); $res = DB::table('test')->max('age’); $res = DB::table('test')->count(); //6. sql組合語句: //where('列名‘[,'運算符’,‘比較值’]) //whereBetween whereNotBetween whereIn / whereNotIn $res = DB::table('test')->whereBetween('id',[4,7])->get(); $res = DB::table('test')->whereIn('id',[4,7])->get(); //or 語句[orWhere 方法接受與 where 方法相同的參] $res = DB::table('test')->where('id','3')->orWhere('age',23)->get(); //orderBy $res = DB::table('test')->orderBy('id','desc')->get(); //limit $res = DB::table('test')->orderBy('id','desc')->limit(2)->get(); //join 四個參數:內連接,左連接,union : $res = DB::table('test')->join('em ','test.id','=','em.test_id')->get(); //groupBy //having…. //7. 事務 //手動拋出 數據庫的引擎 是innodb 三個過程DB::beginTransaction(),DB::commit(),DB::rollback(); DB::beginTransaction(); try{ DB::table('test')->where('id',4)->decrement('age',4); //throw new \Exception('出問題了'); DB::table('test')->where('id',6)->increment('age',4); DB::commit(); }catch(\Exception $e){ echo $e->getMessage(); DB::rollback(); } //自動操做 DB::transaction(function () { DB::table('test')->where('id',4)->decrement('age',4); DB::table('test')->where('id',222)->increment('age',4); });
use Illuminate\Database\Eloquent\Model;
// 時間默認存儲的是 年月日 時分秒 public $timestamps = false; //修改 存儲時間格式 爲字符串 protected $dateFormat = 'U’; 自定義用於存儲時間戳的字段名 const CREATED_AT = ‘login_time’; const UPDATED_AT = reg_time';
類名::insert() //和DB的用發基本同樣,返回bool 類名::insertGetId() //返回插入的id save() 方法 //返回bool 類名::create() //返回實例模型 //須要先在你的模型上指定 fillable 或 guarded 的屬性 protected $fillable = [] 能夠賦值的白名單 protected $guarded = [] 能夠賦值的黑名單
//第一種 $user = self::find(1); $user->name='liming'; $user->save(); //Eloquent 也會假定每一個數據表都有一個名爲 id 的主鍵字段。你能夠定義一個受保護的 $primaryKey 屬性來覆蓋這個約定。例如:protected $primaryKey =‘uid’; 修改主鍵名 //第二種 self::where('uid',2)->update(['name'=>'xiaolizi']);
//第一種 $user = self::find(1); return $user->delete(); //第二種 $user = self::destroy(2); //主鍵 //第三種 $user = self::where('uid',3)->delete();
返回數據 toArray() //獲取一條數據 $user = self::find(4); // 查詢一條數據 主鍵默認 返回模型實例 $user = self::first() //獲取多條數據 $user = self::all()//查詢全部數據 返回數據集 $user = self::get()//查詢全部數據 返回數據集,和查詢構造器用法同樣
一個User 對應一個 Mobile public function mobile(){ return $this->hasOne('App\Model\MobileModel’,’foregin_id’,’local_id’); //第一個參數是Mobile模型,第二個參數關聯的鍵,默認是模型_id,第三個參數是Mobile模型id } //使用 $mobile = self::find(4)->mobile->toArray(); $mobile = self::find(4)->mobile()->value('mobile');
public function address(){ return $this->hasMany('App\Model\AddressModel','user_id'); } //hasMany 和 hasOne 用法同樣 $mobile = self::find(4)->mobile $mobile = self::find(4)->mobile()->value('mobile');
查詢構造器分頁 $users = DB::table('lampol_user')->paginate(3); ORM分頁 self::paginate(4); //簡單的分頁 simplePaginate(15) 視圖展現 引入 bootstrap return view('index',['page'=>$page]);
添加查詢參數到分頁 {{ $page->appends(['vip' => 'y'])->links() }}
框架對錶單傳過來的數據內置了一套機制,進行數據的合法性驗證。
use Illuminate\Support\Facades\Validator; $validator = Validator::make($data,$rules[,$messages]);//(參數一:是要驗證的數據,參數二:是驗證規則,參數三: 錯誤提示信息選填 $rules = [‘username’=>’required’]; $messages = [‘username.required’=>’用戶名不能爲空’];
$validator->fails(); //不經過 返回true 不然返回false $validator->passes(); //經過 返回true 不然返回 false
$validator->errors()->first(); //獲取第一個錯誤信息 $validator->errors()->all(); //獲取全部錯誤信息
email //必須是email格式 numeric //必須是整數 ip //必須是ip地址 required //必須 不爲空 url // 必須是url地址 max //字段的最大值 min //字段的最小值 between:min,max // 字段值的範圍
Validator::extend('mobile', function($attribute, $value, $parameters){ return preg_match('/^1[34578][0-9]{9}$/', $value); });//屬性名稱 $attribute、屬性的值 $value、傳入驗證規則的參數數組 $parameter //添加 錯誤提示信息 resources\lang\en\validation.php
第二種方式:在app下面建立一個Rules文件夾 而後建立一個驗證文件 CheckMobile.php
<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class CheckMobile implements Rule{ public function passes($attribute, $value){ return preg_match('/^1[34578][0-9]{9}$/', $value); } public function message(){ return '電話好默哀好像不太對吧大兄弟'; } }
而後使用
use App\Rules\CheckMobile; $rules = ['phone'=>new CheckMobile]; // [‘phone’=>[‘require’, new CheckMobile]]
配置文件有兩個地方
env(配置名) :獲取根目錄下面的 .env文件 //
.env文件主要存一些隨環境變化而變化的配置,不會被加到版本管理系統
讀裏面env的配置,只放部分配置.
config(文件名.key); 訪問config目錄下面的配置
Laravel 包含各類各樣的全局「輔助」PHP 函數,框架自己也大量地使用了這些功能;若是你以爲方便,你能夠在你的應用中自由的使用它們。
app_path() //獲取app目錄的全路徑 base_path() //項目目錄的路徑 config_path() //配置文件 config全路徑 database_path() //database目錄全路徑 public_path() //public 目錄全路徑 resource_path() //resource 目錄全路徑 storage_path() //storage 目錄全路徑
action(‘UserController@index’) 獲取 路由 asset(‘js/app.js’) //靜態資源路徑 secure_asset(‘js/app.js’) //https 靜態資源路徑 url(‘user’) //路由生成全路徑url secure_url(‘user’) //路由生成https路徑
camel_case('hello_world’); 函數將給定的值符傳轉換爲「駝峯命名」helloWorld kebab_case('helloWorld’);函數將給定的字符串轉換爲「短橫線命名」hello-world snake_case('helloWorld’); 函數將給定的字符串轉換爲「蛇形命名」hello_world starts_with('hello world', 'hello’) //true ends_with('hello world', 'd’) //true str_limit('hello world', '3’) // hel... str_random(4) //函數生成一個指定長度的隨機字符串
array_add([‘name’=>‘liudehua’],‘age’,33) 添加鍵值到數組中 array_except(['name'=>'liudehua','age'=>33],['age’]) 從數組中刪除給定的鍵/值對 array_has([‘name’=>‘liudehua’,‘age’=>33],[‘age’]) 判斷數組是否有鍵 array_only([‘name’=>‘liudehua’,‘age’=>33],[‘age’]) 獲取指定的鍵值 array_random([‘name’=>‘liudehua’,‘age’=>33]) 隨機返回數組值 head([‘name’=>‘liudehua’,‘age’=>33]) 返回數組第一個值 last([‘name’=>‘liudehua’,‘age’=>33]) 返回數組最後一個值
app() 函數返回 服務容器 實例 back() 函數生成一個 重定向 HTTP 響應 到用戶以前的位置: config() 函數獲取 配置 變量的值。 env() 函數獲取 環境變量 的值或者返回默認值 cookie() 函數建立一個新的 cookie 實例 session 函數能夠用來獲取或者設置 Session 值 csrf_field() 函數生成包含 CSRF 令牌值的 HTML hidden 表單字段 csrf_token() 函數獲取當前 CSRF 令牌的值 method_field() 函數生成一個 HTML hidden 表單字段 dd() 函數輸出給定的值並結束腳本運行 dump() 函數打印給定的變量 不結束運行 request() 函數返回當前 請求 實例或者獲取輸入項 response 函數建立 響應 實例或者獲取響應工廠實例 view() 函數獲取一個 視圖 實例 redirect() 函數返回一個 重定向 HTTP 響應 info() 函數將信息寫入日誌 logger() 函數能夠將一個 debug 級別的消息寫入到 日誌 中 encrypt() 函數使用 Laravel 的 加密器 對給定的值進行加密 decrypt() 函數使用 Laravel 的 加密器 來解密給定的值
$img = $request->file(‘img’); //獲取上傳圖片的信息 $img->isValid() //驗證圖片合法性 $img->getClientOriginalName(); //獲取圖片名 $img->getClientOriginalExtension(); //獲取圖片擴展名 $img->getClientMimeType(); //獲取圖片mime $img->getClientSize(); //獲取圖片的大小 $img->move($img_path,$img_name) //開始上傳,第一個圖片存放目錄,第二個圖片名
Laravel 驗證碼
gd 庫 以及 fileinfo擴展打開 https://packagist.org/
//1. composer下載驗證碼 `composer require mews/captcha` //2. 配置 添加下面的 config/app.php 'providers' => [ Mews\Captcha\CaptchaServiceProvider::class, ] 'aliases' => [ 'Captcha' => Mews\Captcha\Facades\Captcha::class, ] //3.生成配置 php artisan vendor:publish //4. 輸出 captcha Captcha::src() //5. 驗證驗證碼 $rules = ['cap' => 'required|captcha']; $message = ['cap.captcha'=>'驗證碼不正確啊']; $validator = Validator::make($request->input(), $rules,$message); if($validator->fails()){ dd($validator->errors()->all()); }
‘default’ => env(‘LOG_CHANNEL’, ‘stack’), //默認配置single一個日誌文件,daily天天一個日誌文件,第二個參數 能夠帶數據
use Illuminate\Support\Facades\Log; Log::info('hello this is info'); Log::debug('hello this is debug'); Log::notice('hello this is notice'); Log::warning('hello this is warning'); Log::error('hello this is error'); Log::critical('hello this is critical'); Log::alert('hello this is alert'); Log::emergency('hello this is emergency’);
logger(‘Debug message’); //debug 級別 logger()->error(‘error’);
php astisan list 列出全部的參數 php artisan key:generate 從新生成 app key php artisan cache:clear 清空緩存 php artisan config:clear 清空配置緩存 php artisan route:clear 清空配置緩存 php artisan view:clear 清空視圖緩存 php artisan route:list 列出配置的路由 //建立控制器 php artisan make:controller OrderController php artisan make:controller Admin/OrderController php artisan make:controller TestController -r 建立模型 php artisan make:model TestModel php artisan make:model Admin\TestModel 建立規則 php artisan make:rule CheckEmail
use Illuminate\Support\Facades\Log; use Log;
config/app.php alias 別名配置