安装方法一: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 别名配置