laravel 速查表
menu

《laravel 速查表》 | laravel china 社区-金年会app官方网

artisan

// 针对命令显示帮助信息
php artisan --help or -h
// 抑制输出信息
php artisan --quiet or -q
// 打印 laravel 的版本信息
php artisan --version or -v
// 不询问任何交互性的问题
php artisan --no-interaction or -n
// 强制输出 ansi 格式
php artisan --ansi
// 禁止输出 ansi 格式
php artisan --no-ansi
// 显示当前命令行运行的环境
php artisan --env
// -v|vv|vvv 通过增加 v 的个数来控制命令行输出内容的详尽情况: 1 个代表正常输出, 2 个代表输出更多消息, 3 个代表调试
php artisan --verbose
// 移除编译优化过的文件 (storage/frameworks/compiled.php)
php artisan clear-compiled
// 显示当前框架运行的环境
php artisan env
// 显示某个命令的帮助信息
php artisan help
// 显示所有可用的命令
php artisan list
// 进入应用交互模式
php artisan tinker
// 配合 dump() 函数调试数据
php artisan dump-server
// 进入维护模式
php artisan down
// 退出维护模式
php artisan up
// 优化框架性能
 // --force    强制编译已写入文件 (storage/frameworks/compiled.php)
 // --psr      不对 composer 的 dump-autoload 进行优化
php artisan optimize [--force] [--psr]
// 更改前端预设
// type_name (可以是 none, bootstrap, vue, react)
php artisan preset [options] [--] type_name
// 启动内置服务器
php artisan serve
// 更改默认端口
php artisan serve --port 8080
// 使其在本地服务器外也可正常工作
php artisan serve --host 0.0.0.0
// 更改应用命名空间
php artisan app:name namespace
// 清除过期的密码重置令牌
php artisan auth:clear-resets
// 清空应用缓存
php artisan cache:clear
// 移除 key_name 对应的缓存
php artisan cache:forget key_name []
// 创建缓存数据库表 migration
php artisan cache:table
// 合并所有的配置信息为一个,提高加载速度
php artisan config:cache
// 移除配置缓存文件
php artisan config:clear
// 程序内部调用 artisan 命令
$exitcode = artisan::call('config:cache');
// 运行所有的 seed 假数据生成类
 // --class      可以指定运行的类,默认是: "databaseseeder"
 // --database   可以指定数据库
 // --force      当处于生产环境时强制执行操作
php artisan db:seed [--class[="..."]] [--database[="..."]] [--force]
// 基于注册的信息,生成遗漏的 events 和 handlers
php artisan event:generate
// 罗列所有事件和监听器
php artisan event:list
// 缓存事件和监听器
php artisan event:cache
// 清除事件和监听器缓存
php artisan event:clear
// 生成新的处理器类
 // --command      需要处理器处理的命令类名字
php artisan handler:command [--command="..."] name
// 创建一个新的时间处理器类
 // --event        需要处理器处理的事件类名字
 // --queued       需要处理器使用队列话处理的事件类名字
php artisan handler:event [--event="..."] [--queued] name
// 生成应用的 key(会覆盖)
php artisan key:generate
// 发布本地化翻译文件到 resources 文件下
// locales: 逗号分隔,如 zh_cn,tk,th [默认是: "all"]
php artisan lang:publish [options] [--] []
// 创建用户认证脚手架
php artisan make:auth
// 创建 channel 类
php artisan make:channel name
// 在默认情况下, 这将创建未加入队列的自处理命令
 // 通过 --handler 标识来生成一个处理器, 用 --queued 来使其入队列.
php artisan make:command [--handler] [--queued] name
// 创建一个新的 artisan 命令
 //  --command     命令被调用的名称。 (默认为: "command:name")
php artisan make:console [--command[="..."]] name
// 创建一个新的资源控制器
 // --plain      生成一个空白的控制器类
php artisan make:controller [--plain] name
php artisan make:controller app\\admin\\http\\controllers\\dashboardcontroller
// 创建一个新的事件类
php artisan make:event name
// 创建异常类
php artisan make:exception name
// 创建模型工厂类
php artisan make:factory name
// 创建一个队列任务文件
php artisan make:job 
// 创建一个监听者类
php artisan make:listener name
// 创建一个新的邮件类
php artisan make:mail name
// 创建一个新的中间件类
php artisan make:middleware name
// 创建一个新的迁移文件
 // --create     将被创建的数据表.
 // --table      将被迁移的数据表.
php artisan make:migration [--create[="..."]] [--table[="..."]] name
// 创建一个新的 eloquent 模型类
php artisan make:model user
php artisan make:model models/user
// 新建一个消息通知类
php artisan make:notification topicrepliednotification
// 新建一个模型观察者类
php artisan make:observer userobserver
// 创建授权策略
php artisan make:policy postpolicy
// 创建一个新的服务提供者类
php artisan make:provider name
// 创建一个新的表单请求类
php artisan make:request name
// 创建一个 api 资源类
php artisan make:resource name
// 新建验证规则类
php artisan make:rule name
// 创建模型脚手架
//  模型名称,如 post
// -s, --schema=schema 表结构如:--schema="title:string"
// -a, --validator[=validator] 表单验证,如:--validator="title:required"
// -l, --localization[=localization] 设置本地化信息,如:--localization="key:value"
// -b, --lang[=lang] 设置本地化语言 --lang="en"
// -f, --form[=form] 使用 illumintate/html form 来生成表单选项,默认为 false
// -p, --prefix[=prefix] 表结构前缀,默认 false
php artisan make:scaffold  [options] [--] 
// 生成数据填充类
php artisan make:seeder
// 生成测试类
php artisan make:test
// 数据库迁移
 // --database   指定数据库连接(下同)
 // --force      当处于生产环境时强制执行,不询问(下同)
 // --path       指定单独迁移文件地址
 // --pretend    把将要运行的 sql 语句打印出来(下同)
 // --seed       seed 任务是否需要被重新运行(下同)
php artisan migrate [--database[="..."]] [--force] [--path[="..."]] [--pretend] [--seed]
// 创建迁移数据库表
php artisan migrate:install [--database[="..."]]
// drop 所有数据表并重新运行 migration
php artisan migrate:fresh
// 重置并重新运行所有的 migrations
 // --seeder     指定主 seeder 的类名
php artisan migrate:refresh [--database[="..."]] [--force] [--seed] [--seeder[="..."]]
// 回滚所有的数据库迁移
php artisan migrate:reset [--database[="..."]] [--force] [--pretend]
// 回滚最最近一次运行的迁移任务
php artisan migrate:rollback [--database[="..."]] [--force] [--pretend]
// migrations 数据库表信息
php artisan migrate:status
// 为数据库消息通知创建一个表迁移类
php artisan notifications:table
// 清除缓存的 bootstrap 文件
php artisan optimize:clear
// 扩展包自动发现
php artisan package:discover
// 为队列数据库表创建一个新的迁移
php artisan queue:table
// 监听指定的队列
 // --queue      被监听的队列
 // --delay      给执行失败的任务设置延时时间 (默认为零: 0)
 // --memory     内存限制大小,单位为 mb (默认为: 128)
 // --timeout    指定任务运行超时秒数 (默认为: 60)
 // --sleep      等待检查队列任务的秒数 (默认为: 3)
 // --tries      任务记录失败重试次数 (默认为: 0)
php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// 查看所有执行失败的队列任务
php artisan queue:failed
// 为执行失败的数据表任务创建一个迁移
php artisan queue:failed-table
// 清除所有执行失败的队列任务
php artisan queue:flush
// 删除一个执行失败的队列任务
php artisan queue:forget
// 在当前的队列任务执行完毕后, 重启队列的守护进程
php artisan queue:restart
// 对指定 id 的执行失败的队列任务进行重试(id: 失败队列任务的 id)
php artisan queue:retry id
// 指定订阅 iron.io 队列的链接
 // queue: iron.io 的队列名称.
 // url: 将被订阅的 url.
 // --type       指定队列的推送类型.
php artisan queue:subscribe [--type[="..."]] queue url
// 处理下一个队列任务
 // --queue      被监听的队列
 // --daemon     在后台模式运行
 // --delay      给执行失败的任务设置延时时间 (默认为零: 0)
 // --force      强制在「维护模式下」运行
 // --memory     内存限制大小,单位为 mb (默认为: 128)
 // --sleep      当没有任务处于有效状态时, 设置其进入休眠的秒数 (默认为: 3)
 // --tries      任务记录失败重试次数 (默认为: 0)
php artisan queue:work [--queue[="..."]] [--daemon] [--delay[="..."]] [--force] [--memory[="..."]] [--sleep[="..."]] [--tries[="..."]] [connection]
// 生成路由缓存文件来提升路由效率
php artisan route:cache
// 移除路由缓存文件
php artisan route:clear
// 显示已注册过的路由
php artisan route:list
// 运行计划命令
php artisan schedule:run
// 为 session 数据表生成迁移文件
php artisan session:table
// 创建 "public/storage" 到 "storage/app/public" 的软链接
php artisan storage:link
// 从 vendor 的扩展包中发布任何可发布的资源
 // --force        重写所有已存在的文件
 // --provider     指定你想要发布资源文件的服务提供者
 // --tag          指定你想要发布标记资源.
php artisan vendor:publish [--force] [--provider[="..."]] [--tag[="..."]]
php artisan tail [--path[="..."]] [--lines[="..."]] [connection]
// 缓存视图文件以提高效率
php artisan view:cache
// 清除视图文件缓存
php artisan view:clear

pagination

// 自动处理分页逻辑
model::paginate(15);
model::where('cars', 2)->paginate(15);
// 使用简单模板 - 只有 "上一页" 或 "下一页" 链接
model::where('cars', 2)->simplepaginate(15);
// 手动分页
paginator::make($items, $totalitems, $perpage);
// 在页面打印分页导航栏
$variable->links();
// 获取当前页数据数量。
$results->count()
// 获取当前页页码。
$results->currentpage()
// 获取结果集中第一条数据的结果编号。
$results->firstitem()
// 获取分页器选项。
$results->getoptions()
// 创建分页 url 范围。
$results->geturlrange($start, $end)
// 是否有多页。
$results->hasmorepages()
// 获取结果集中最后一条数据的结果编号。
$results->lastitem()
// 获取最后一页的页码(在 `simplepaginate` 中无效)。
$results->lastpage()
// 获取下一页的 url 。
$results->nextpage
// 当前而是否为第一页。
$results->onfirstpage()
// 每页的数据条数。
$results->perpage()
// 获取前一页的 url。
$results->previouspage
// 数据总数(在 `simplepaginate` 无效)。
$results->total()
// 获取指定页的 url。
$results->

lang

app::setlocale('en');
lang::get('messages.welcome');
lang::get('messages.welcome', array('foo' => 'bar'));
lang::has('messages.welcome');
lang::choice('messages.apples', 10);
// lang::get 的别名
trans('messages.welcome');
// lang::choice 的别名
trans_choice('messages.apples',  10)
// 辅助函数
__('messages.welcome')

file

file::exists($path);
file::get($path, $lock = false);
// 加锁读取文件内容
file::sharedget($path);
// 获取文件内容,不存在会抛出 filenotfoundexception 异常
file::getrequire($path);
// 获取文件内容, 仅能引入一次
file::requireonce($file);
// 生成文件路径的 md5 哈希
file::hash($path);
// 将内容写入文件
file::put($path, $contents, $lock = false);
// 写入文件,存在的话覆盖写入
file::replace($path, $content);
// 将内容添加在文件原内容前面
file::prepend($path, $data);
// 将内容添加在文件原内容后
file::append($path, $data);
// 修改路径权限
file::chmod($path, $mode = null);
// 通过给定的路径来删除文件
file::delete($paths);
// 将文件移动到新目录下
file::move($path, $target);
// 将文件复制到新目录下
file::copy($path, $target);
// 创建硬连接
file::link($target, $link);
// 从文件路径中提取文件名,不包含后缀
file::name($path);
// 从文件路径中提取文件名,包含后缀
file::basename($path);
// 获取文件路径名称
file::dirname($path);
// 从文件的路径地址提取文件的扩展
file::extension($path);
// 获取文件类型
file::type($path);
// 获取文件 mime 类型
file::mimetype($path);
// 获取文件大小
file::size($path);
// 获取文件的最后修改时间
file::lastmodified($path);
// 判断给定的路径是否是文件目录
file::isdirectory($directory);
// 判断给定的路径是否是可读取
file::isreadable($path);
// 判断给定的路径是否是可写入的
file::iswritable($path);
// 判断给定的路径是否是文件
file::isfile($file);
// 查找能被匹配到的路径名
file::glob($pattern, $flags = 0);
// 获取一个目录下的所有文件, 以数组类型返回
file::files($directory, $hidden = false);
// 获取一个目录下的所有文件 (递归).
file::allfiles($directory, $hidden = false);
// 获取一个目录内的目录
file::directories($directory);
// 创建一个目录
file::makedirectory($path, $mode = 0755, $recursive = false, $force = false);
// 移动目录
file::movedirectory($from, $to, $overwrite = false);
// 将文件夹从一个目录复制到另一个目录下
file::copydirectory($directory, $destination, $options = null);
// 删除目录
file::deletedirectory($directory, $preserve = false);
// 递归式删除目录
file::deletedirectories($directory);
// 清空指定目录的所有文件和文件夹
file::cleandirectory($directory);

schema

// 创建指定数据表
 schema::create('table', function($table)
{
  $table->increments('id');
});
// 指定一个连接
 schema::connection('foo')->create('table', function($table){});
// 通过给定的名称来重命名数据表
 schema::rename($from, $to);
// 移除指定数据表
 schema::drop('table');
// 当数据表存在时, 将指定数据表移除
 schema::dropifexists('table');
// 判断数据表是否存在
 schema::hastable('table');
// 判断数据表是否有该列
 schema::hascolumn('table', 'column');
// 获取数据表字段列表
 schema::getcolumnlisting('table');
// 更新一个已存在的数据表
 schema::table('table', function($table){});
// 重命名数据表的列
$table->renamecolumn('from', 'to');
// 移除指定的数据表列
$table->dropcolumn(string|array);
// 指定数据表使用的存储引擎
$table->engine = 'innodb';
// 字段顺序,只能在 mysql 中才能用
$table->string('name')->after('email');

索引

$table->string('column')->unique();
$table->primary('column');
// 创建一个双主键
$table->primary(array('first', 'last'));
$table->unique('column');
$table->unique('column', 'key_name');
// 创建一个双唯一性索引
$table->unique(array('first', 'last'));
$table->unique(array('first', 'last'), 'key_name');
$table->index('column');
$table->index('column', 'key_name');
// 创建一个双索引
$table->index(array('first', 'last'));
$table->index(array('first', 'last'), 'key_name');
$table->dropprimary(array('column'));
$table->dropprimary('table_column_primary');
$table->dropunique(array('column'));
$table->dropunique('table_column_unique');
$table->dropindex(array('column'));
$table->dropindex('table_column_index');

外键

$table->foreign('user_id')->references('id')->on('users');
$table->foreign('user_id')->references('id')->on('users')->ondelete('cascade'|'restrict'|'set null'|'no action');
$table->foreign('user_id')->references('id')->on('users')->onupdate('cascade'|'restrict'|'set null'|'no action');
$table->dropforeign(array('user_id'));
$table->dropforeign('posts_user_id_foreign');

字段类型

// 自增
$table->increments('id');
$table->bigincrements('id');
// 数字
$table->integer('votes');
$table->tinyinteger('votes');
$table->smallinteger('votes');
$table->mediuminteger('votes');
$table->biginteger('votes');
$table->float('amount');
$table->double('column', 15, 8);
$table->decimal('amount', 5, 2);
// 字符串和文本
$table->char('name', 4);
$table->string('email');
$table->string('name', 100);
$table->text('description');
$table->mediumtext('description');
$table->longtext('description');
// 日期和时间
$table->date('created_at');
$table->datetime('created_at');
$table->time('sunrise');
$table->timestamp('added_on');
// adds created_at and updated_at columns
 // 添加 created_at 和 updated_at 行
$table->timestamps();
$table->nullabletimestamps();
// 其它类型
$table->binary('data');
$table->boolean('confirmed');
// 为软删除添加 deleted_at 字段
$table->softdeletes();
$table->enum('choices', array('foo', 'bar'));
// 添加 remember_token 为 varchar(100) null
$table->remembertoken();
// 添加整型的 parent_id 和字符串类型的 parent_type
$table->morphs('parent');
->nullable()
->default($value)
->unsigned()
->comment()

auth

用户认证

// 获取 auth 对象,等同于 auth facade
auth();
// 判断当前用户是否已认证(是否已登录)
auth::check();
// 判断当前用户是否未登录,与 check() 相反
auth::guest();
// 自定义看守器 默认为 `web`
auth::guard();
// 获取当前的认证用户
auth::user();
// 获取当前的认证用户的 id(未登录情况下会报错)
auth::id();
// 通过给定的信息来尝试对用户进行认证(成功后会自动启动会话)
auth::attempt(['email' => $email, 'password' => $password]);
// 通过 auth::attempt() 传入 true 值来开启 '记住我' 功能
auth::attempt($credentials, true);
// 注册尝试登录的事件监听器
auth::attempting($callback);
// 只针对一次的请求来认证用户
auth::once($credentials);
// 使用 id 登录,无 cookie 和会话登录
auth::onceusingid($id);
// 登录一个指定用户到应用上
auth::login(user::find(1), $remember = false);
// 检测是否记住了登录
auth::viaremember();
// 登录指定用户 id 的用户到应用上
auth::loginusingid(1, $remember = false);
// 使用户退出登录(清除会话)
auth::logout();
// 清除当前用户的其他会话
auth::logoutotherdevices('password', $attribute = 'password');
// 验证用户凭证
auth::validate($credentials);
// 使用 http 的基本认证方式来认证
auth::basic('username');
// 执行「http basic」登录尝试,只认证一次
auth::oncebasic();
// 发送密码重置提示给用户
password::remind($credentials, function($message, $user){});

用户授权

// 定义权限
gate::define('update-post', 'class@method');
gate::define('update-post', function ($user, $post) {...});
// 传递多个参数
gate::define('delete-comment', function ($user, $post, $comment) {});
// 一次性的定义多个 gate 方法
gate::resource('posts',  'app\policies\postpolicy');
// 检测权限是否被定义
gate::has('update-post');
// 检查权限
gate::denies('update-post', $post);
gate::allows('update-post', $post);
gate::check('update-post', $post);
// 指定用户进行检查
gate::foruser($user)->allows('update-post', $post);
// 在 user 模型下,使用 authorizable trait
user::find(1)->can('update-post', $post);
user::find(1)->cannot('update-post', $post);
user::find(1)->cant('update-post', $post);
// 拦截所有检查,返回 bool
gate::before(function ($user, $ability) {});
// 设置每一次验证的回调
gate::after(function ($user, $ability, $result, $arguments) {});
// blade 模板语法
@can('update-post', $post)
@endcan
// 支持 else 表达式
@can('update-post', $post)
@else
@endcan
// 无权限判断
@cannot
@endcannot
// 生成一个新的策略
php artisan make:policy postpolicy
php artisan make:policy postpolicy --model=post
// `policy` 帮助函数
policy($post)->update($user, $post)
// 控制器授权
$this->authorize('update', $post);
// 指定用户 $user 授权
$this->authorizeforuser($user, 'update', $post);
// 控制器的 __construct 中授权资源控制器
$this->authorizeresource(post::class,  'post');
// authserviceprovider->boot() 里修改策略自动发现的逻辑
gate::guesspolicynamesusing(function ($modelclass) {
    // 返回模型对应的策略名称,如:// 'app\model\user' => 'app\policies\userpolicy',
    return 'app\policies\\'.class_basename($modelclass).'policy';
});
// 中间件指定模型实例
route::put('/post/{post}',  function  (post $post)  { ... })->middleware('can:update,post');
// 中间件未指定模型实例
route::post('/post',  function  ()  { ... })->middleware('can:create,app\post');

helper

注:数组和字符串函数将在 5.9 全面废弃,推荐使用 arr 和 str facade

数组 & 对象

// 如果给定的键不存在于该数组,arr::add 函数将给定的键值对加到数组中
arr::add(['name' => 'desk'], 'price', 100); 
// >>> ['name' => 'desk', 'price' => 100]
// 将数组的每一个数组折成单一数组
arr::collapse([[1, 2, 3], [4, 5, 6]]);  
// >>> [1, 2, 3, 4, 5, 6]
// 函数返回两个数组,一个包含原本数组的键,另一个包含原本数组的值
arr::divide(['key1' => 'val1', 'key2' =>'val2'])
// >>> [["key1","key2"],["val1","val2"]]
// 把多维数组扁平化成一维数组,并用「点」式语法表示深度
arr::dot($array);
// 从数组移除给定的键值对
arr::except($array, array('key'));
// 返回数组中第一个通过真值测试的元素
arr::first($array, function($value, $key){}, $default);
// 将多维数组扁平化成一维
 // ['joe', 'php', 'ruby'];
arr::flatten(['name' => 'joe', 'languages' => ['php', 'ruby']]);
// 以「点」式语法从深度嵌套数组移除给定的键值对
arr::forget($array, 'foo');
arr::forget($array, 'foo.bar');
// 使用「点」式语法从深度嵌套数组取回给定的值
arr::get($array, 'foo', 'default');
arr::get($array, 'foo.bar', 'default');
// 使用「点」式语法检查给定的项目是否存在于数组中
arr::has($array, 'products.desk');
// 从数组返回给定的键值对
arr::only($array, array('key'));
// 从数组拉出一列给定的键值对
arr::pluck($array, 'key');
// 从数组移除并返回给定的键值对
arr::pull($array, 'key');
// 使用「点」式语法在深度嵌套数组中写入值
arr::set($array, 'key', 'value');
arr::set($array, 'key.subkey', 'value');
// 借由给定闭包结果排序数组
arr::sort($array, function(){});
// 使用 sort 函数递归排序数组
arr::sortrecursive();
// 使用给定的闭包过滤数组
arr::where();
// 数组"洗牌"
arr::shuffle($array,'i-am-groot');
// 数组包裹(如果不是数组,就变成数组,如果是空的,返回[],否则返回原数据)
arr::wrap($array);
// 返回给定数组的第一个元素
head($array);
// 返回给定数组的最后一个元素
last($array);

路径

// 取得 app 文件夹的完整路径
app_path();
// 取得项目根目录的完整路径
base_path();
// 取得应用配置目录的完整路径
config_path();
// 取得应用数据库目录的完整路径
database_path();
// 取得加上版本号的 elixir 文件路径
elixir();
// 取得 public 目录的完整路径
public_path();
// 取得 storage 目录的完整路径
storage_path();

字符串

// 将给定的字符串转换成 驼峰式命名
str::camel($value);
// 返回不包含命名空间的类名称
class_basename($class);
class_basename($object);
// 对给定字符串运行 htmlentities
e('');
// 判断字符串开头是否为给定内容
str::startswith('foo bar.', 'foo');
// 判断给定字符串结尾是否为指定内容
str::endswith('foo bar.', 'bar.');
// 将给定的字符串转换成 蛇形命名
str::snake('foobar');
// 将给定字符串转换成「首字大写命名」: foobar
str::studly('foo_bar');
// 根据你的本地化文件翻译给定的语句
trans('foo.bar');
// 根据后缀变化翻译给定的语句
trans_choice('foo.bar', $count);

urls and links

// 产生给定控制器行为网址
action('foocontroller@method', $parameters);
// 根据目前请求的协定(http 或 https)产生资源文件网址
asset('img/photo.jpg', $title, $attributes);
// 根据 https 产生资源文件网址
secure_asset('img/photo.jpg', $title, $attributes);
// 产生给定路由名称网址
route($route, $parameters, $absolute = true);
// 产生给定路径的完整网址
url('path', $parameters = array(), $secure = null);

其他

// 返回一个认证器实例。你可以使用它取代 auth facade
auth()->user();
// 产生一个重定向回应让用户回到之前的位置
back();
// 使用 bcrypt 哈希给定的数值。你可以使用它替代 hash facade
bcrypt('my-secret-password');
// 从给定的项目产生集合实例
collect(['taylor', 'abigail']);
// 取得设置选项的设置值
config('app.timezone', $default);
// 产生包含 csrf 令牌内容的 html 表单隐藏字段
{!! csrf_field() !!} 
// 5.7 用这个
@csrf
// 取得当前 csrf 令牌的内容
$token = csrf_token();
// 输出给定变量并结束脚本运行
dd($value);
// var_dump缩写(如果用dump-server,var_dump可能无效)
dump($value);
// 取得环境变量值或返回默认值
$env = env('app_env');
$env = env('app_env', 'production');
// 配送给定事件到所属的侦听器
event(new userregistered($user));
// 根据给定类、名称以及总数产生模型工厂建构器
$user = factory(app\user::class)->make();
// 产生拟造 http 表单动作内容的 html 表单隐藏字段
{!! method_field('delete') !!}
// 5.7 
@method('delete')
// 取得快闪到 session 的旧有输入数值
$value = old('value');
$value = old('value', 'default');
// 返回重定向器实例以进行 重定向
 return redirect('/home');
// 取得目前的请求实例或输入的项目
$value = request('key', $default = null)
// 创建一个回应实例或获取一个回应工厂实例
return response('hello world', 200, $headers);
// 可被用于取得或设置单一 session 内容
$value = session('key');
// 在没有传递参数时,将返回 session 实例
$value = session()->get('key');
session()->put('key', $value);
// 返回给定数值
value(function(){ return 'bar'; });
// 取得视图 实例
return view('auth.login');
// 返回给定的数值
$value = with(new foo)->work();

composer

composer create-project laravel/laravel folder_name
composer create-project laravel/laravel folder_name --prefer-dist "5.8.*"
composer install
composer install --prefer-dist
composer update
composer update package/name
composer dump-autoload [--optimize]
composer self-update
composer require [options] [--] [vendor/packages]...
// 全局安装
composer require global vendor/packages
// 罗列所有扩展包括版本信息
composer show

environment

$environment = app()->environment();
$environment = app::environment();
// 判断当环境是否为 local
if (app()->environment('local')){}
// 判断当环境是否为 local 或 staging...
if (app()->environment(['local', 'staging'])){}

log

// 记录器提供了 7 种在 rfc 5424 标准内定义的记录等级:
// debug, info, notice, warning, error, critical, and alert.
log::info('info');
log::info('info',array('context'=>'additional info'));
log::error('error');
log::warning('warning');
// 获取 monolog 实例
log::getmonolog();
// 添加监听器
log::listen(function($level, $message, $context) {});

记录 sql 查询语句

// 开启 log
db::connection()->enablequerylog();
// 获取已执行的查询数组
db::getquerylog();

url

url::full();
url::current();
url::previous();
url::to('foo/bar', $parameters, $secure);
url::action('newscontroller@item', ['id'=>123]);
// 需要在适当的命名空间内
url::action('auth\authcontroller@logout');
url::action('foocontroller@method', $parameters, $absolute);
url::route('foo', $parameters, $absolute);
url::secure('foo/bar', $parameters);
url::asset('css/foo.css', $secure);
url::secureasset('css/foo.css');
url::isvalid;
url::getrequest();
url::setrequest($request);

event

// 1. eventserviceprovider 类里的 $listen 属性
protected $listen =['app\events\ordershipped' => ['app\listeners\sendshipmentnotification']];
// 2. 生成监听类
php artisan event:generate
// 触发命令
event::dispatch($event, $payload = [], $halt = false);
event($event, $payload = [], $halt = false);
// 触发命令并等待
event::until($event, $payload = []);
// 注册一个事件监听器.
// void listen(string|array $events, mixed $listener, int $priority)
event::listen('app\events\usersignup', function($bar){});
event::listen('event.*', function($bar){}); // 通配符监听器
event::listen('foo.bar', 'foohandler', 10);
event::listen('foo.bar', 'barhandler', 5);
// 你可以直接在处理逻辑中返回 false 来停止一个事件的传播.
event::listen('foor.bar', function($event){ return false; });
event::subscribe('usereventhandler');
// 获取所有监听者
event::getlisteners($eventname);
// 移除事件及其对应的监听者
event::forget($event);
// 将事件推入堆栈中等待执行
event::push($event, $payload = []);
// 移除指定的堆栈事件
event::flush($event);
// 移除所有堆栈中的事件
event::forgetpushed();

db

基本使用

db::connection('connection_name');
// 运行数据库查询语句
$results = db::select('select * from users where id = ?', [1]);
$results = db::select('select * from users where id = :id', ['id' => 1]);
// 运行普通语句
db::statement('drop table users');
// 监听查询事件
db::listen(function($sql, $bindings, $time) { code_here; });
// 数据库事务处理
db::transaction(function() {
    db::table('users')->update(['votes' => 1]);
    db::table('posts')->delete();
});
db::begintransaction();
db::rollback();
db::commit();
// 获取表前缀
db::gettableprefix()

查询语句构造器 

// 取得数据表的所有行
db::table('name')->get();
// 取数据表的部分数据
db::table('users')->chunk(100, function($users) {
  foreach ($users as $user) {
      //
  }
});
// 取回数据表的第一条数据
$user = db::table('users')->where('name', 'john')->first();
db::table('name')->first();
// 从单行中取出单列数据
$name = db::table('users')->where('name', 'john')->pluck('name');
db::table('name')->pluck('column');
// 取多行数据的「列数据」数组
$roles = db::table('roles')->lists('title');
$roles = db::table('roles')->lists('title', 'name');
// 指定一个选择字段
$users = db::table('users')->select('name', 'email')->get();
$users = db::table('users')->distinct()->get();
$users = db::table('users')->select('name as user_name')->get();
// 添加一个选择字段到一个已存在的查询语句中
$query = db::table('users')->select('name');
$users = $query->addselect('age')->get();
// 使用 where 运算符
$users = db::table('users')->where('votes', '>', 100)->get();
$users = db::table('users')
              ->where('votes', '>', 100)
              ->orwhere('name', 'john')
              ->get();
$users = db::table('users')
      ->wherebetween('votes', [1, 100])->get();
$users = db::table('users')
      ->wherenotbetween('votes', [1, 100])->get();
$users = db::table('users')
      ->wherein('id', [1, 2, 3])->get();
$users = db::table('users')
      ->wherenotin('id', [1, 2, 3])->get();
$users = db::table('users')
      ->wherenull('updated_at')->get();
db::table('name')->wherenotnull('column')->get();
// 动态的 where 字段
$admin = db::table('users')->whereid(1)->first();
$john = db::table('users')
      ->whereidandemail(2, '[email protected]')
      ->first();
$jane = db::table('users')
      ->wherenameorage('jane', 22)
      ->first();
// order by, group by, 和 having
$users = db::table('users')
      ->orderby('name', 'desc')
      ->groupby('count')
      ->having('count', '>', 100)
      ->get();
db::table('name')->orderby('column')->get();
db::table('name')->orderby('column','desc')->get();
db::table('name')->having('count', '>', 100)->get();
// 偏移 & 限制
$users = db::table('users')->skip(10)->take(5)->get();

joins 

// 基本的 join 声明语句
db::table('users')
    ->join('contacts', 'users.id', '=', 'contacts.user_id')
    ->join('orders', 'users.id', '=', 'orders.user_id')
    ->select('users.id', 'contacts.phone', 'orders.price')
    ->get();
// left join 声明语句
db::table('users')
->leftjoin('posts', 'users.id', '=', 'posts.user_id')
->get();
// select * from users where name = 'john' or (votes > 100 and title <> 'admin')
db::table('users')
    ->where('name', '=', 'john')
    ->orwhere(function($query) {
        $query->where('votes', '>', 100)
              ->where('title', '<>', 'admin');
    })
    ->get();

聚合 

$users = db::table('users')->count();
$price = db::table('orders')->max('price');
$price = db::table('orders')->min('price');
$price = db::table('orders')->avg('price');
$total = db::table('users')->sum('votes');

原始表达句

$users = db::table('users')
                   ->select(db::raw('count(*) as user_count, status'))
                   ->where('status', '<>', 1)
                   ->groupby('status')
                   ->get();
// 返回行
db::select('select * from users where id = ?', array('value'));
db::insert('insert into foo set bar=2');
db::update('update foo set bar=2');
db::delete('delete from bar');
// 返回 void
db::statement('update foo set bar=2');
// 在声明语句中加入原始的表达式
db::table('name')->select(db::raw('count(*) as count, column2'))->get();

inserts / updates / deletes / unions / pessimistic locking

// 插入
db::table('users')->insert(
  ['email' => '[email protected]', 'votes' => 0]
);
$id = db::table('users')->insertgetid(
  ['email' => '[email protected]', 'votes' => 0]
);
db::table('users')->insert([
  ['email' => '[email protected]', 'votes' => 0],
  ['email' => '[email protected]', 'votes' => 0]
]);
// 更新
db::table('users')
          ->where('id', 1)
          ->update(['votes' => 1]);
db::table('users')->increment('votes');
db::table('users')->increment('votes', 5);
db::table('users')->decrement('votes');
db::table('users')->decrement('votes', 5);
db::table('users')->increment('votes', 1, ['name' => 'john']);
// 删除
db::table('users')->where('votes', '<', 100)->delete();
db::table('users')->delete();
db::table('users')->truncate();
// 集合
 // unionall() 方法也是可供使用的,调用方式与 union 相似
$first = db::table('users')->wherenull('first_name');
$users = db::table('users')->wherenull('last_name')->union($first)->get();
// 消极锁
db::table('users')->where('votes', '>', 100)->sharedlock()->get();
db::table('users')->where('votes', '>', 100)->lockforupdate()->get();

unittest

安装和运行

// 将其加入到 composer.json 并更新:
composer require "phpunit/phpunit:4.0.*"
// 运行测试 (在项目根目录下运行)
./vendor/bin/phpunit

断言

$this->asserttrue(true);
$this->assertequals('foo', $bar);
$this->assertcount(1,$times);
$this->assertresponseok();
$this->assertresponsestatus(403);
$this->assertredirectedto('foo');
$this->assertredirectedtoroute('route.name');
$this->assertredirectedtoaction('controller@method');
$this->assertviewhas('name');
$this->assertviewhas('age', $value);
$this->assertsessionhaserrors();
// 由单个 key 值来假定 session 有错误...
$this->assertsessionhaserrors('name');
// 由多个 key 值来假定 session 有错误...
$this->assertsessionhaserrors(array('name', 'age'));
$this->asserthasoldinput();

访问路由

$response = $this->call($method, $uri, $parameters, $files, $server, $content);
$response = $this->callsecure('get', 'foo/bar');
$this->session(['foo' => 'bar']);
$this->flushsession();
$this->seed();
$this->seed($connection);

input

input::get('key');
// 指定默认值
input::get('key', 'default');
input::has('key');
input::all();
// 只取回 'foo' 和 'bar',返回数组
input::only('foo', 'bar');
// 取除了 'foo' 的所有用户输入数组
input::except('foo');
input::flush();
// 字段 'key' 是否有值,返回 boolean
input::filled('key');

会话周期内 input

// 清除会话周期内的输入
input::flash();
// 清除会话周期内的指定输入
input::flashonly('foo', 'bar');
// 清除会话周期内的除了指定的其他输入
input::flashexcept('foo', 'baz');
// 取回一个旧的输入条目
input::old('key','default_value');

files

// 使用一个已上传的文件
input::file('filename');
// 判断文件是否已上传
input::hasfile('filename');
// 获取文件属性
input::file('name')->getrealpath();
input::file('name')->getclientoriginalname();
input::file('name')->getclientoriginalextension();
input::file('name')->getsize();
input::file('name')->getmimetype();
// 移动一个已上传的文件
input::file('name')->move($destinationpath);
// 移动一个已上传的文件,并设置新的名字
input::file('name')->move($destinationpath, $filename);

session

session::get('key');
// 从会话中读取一个条目
 session::get('key', 'default');
session::get('key', function(){ return 'default'; });
// 获取 session 的 id
session::getid();
// 增加一个会话键值数据
session::put('key', 'value');
// 将一个值加入到 session 的数组中
session::push('foo.bar','value');
// 返回 session 的所有条目
session::all();
// 检查 session 里是否有此条目
session::has('key');
// 从 session 中移除一个条目
session::forget('key');
// 从 session 中移除所有条目
session::flush();
// 生成一个新的 session 标识符
session::regenerate();
// 把一条数据暂存到 session 中
session::flash('key', 'value');
// 清空所有的暂存数据
session::reflash();
// 重新暂存当前暂存数据的子集
session::keep(array('key1', 'key2'));

response

return response::make($contents);
return response::make($contents, 200);
return response::json(array('key' => 'value'));
return response::json(array('key' => 'value'))
->setcallback(input::get('callback'));
return response::download($filepath);
return response::download($filepath, $filename, $headers);
// 创建一个回应且修改其头部信息的值
$response = response::make($contents, 200);
$response->header('content-type', 'application/json');
return $response;
// 为回应附加上 cookie
return response::make($content)
->withcookie(cookie::make('key', 'value'));

container

app::bind('foo', function($app){ return new foo; });
app::make('foo');
// 如果存在此类, 则返回
app::make('foobar');
// 单例模式实例到服务容器中
app::singleton('foo', function(){ return new foo; });
// 将已实例化的对象注册到服务容器中
app::instance('foo', new foo);
// 注册绑定规则到服务容器中
app::bind('foorepositoryinterface', 'barrepository');
// 绑定基本值
app::when('app\http\controllers\usercontroller')->needs('$variablename')->give($value);
// 标记
$this->app->tag(['speedreport',  'memoryreport'],  'reports');
// 给应用注册一个服务提供者
app::register('fooserviceprovider');
// 监听容器对某个对象的解析
app::resolving(function($object){});
resolve('helpspot\api');

security

哈希

hash::make('secretpassword');
hash::check('secretpassword', $hashedpassword);
hash::needsrehash($hashedpassword);

加密解密

crypt::encrypt('secretstring');
crypt::decrypt($encryptedstring);
crypt::setmode('ctr');
crypt::setcipher($cipher);

queue

queue::push('sendmail', array('message' => $message));
queue::push('sendemail@send', array('message' => $message));
queue::push(function($job) use $id {});
// 在多个 workers 中使用相同的负载
 queue::bulk(array('sendemail', 'notifyuser'), $payload);
// 开启队列监听器
php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
// 只处理第一个队列任务
php artisan queue:work
// 在后台模式启动一个队列 worker
php artisan queue:work --daemon
// 为失败的任务创建 migration 文件
php artisan queue:failed-table
// 监听失败任务
php artisan queue:failed
// 通过 id 删除失败的任务
php artisan queue:forget 5
// 删除所有失败任务
php artisan queue:flush
// 因为队列不会默认使用 php memory 参数,需要在队列指定(单位默认mb)
php artisan queue:work --memory=50

validation

validator::make(
array('key' => 'foo'),
array('key' => 'required|in:foo')
);
validator::extend('foo', function($attribute, $value, $params){});
validator::extend('foo', 'foovalidator@validate');
validator::resolver(function($translator, $data, $rules, $msgs)
{
return new foovalidator($translator, $data, $rules, $msgs);
});

验证规则

accepted // 待验证字段必须是 yes , on ,1 或 true 
active_url
after:yyyy-mm-dd // 待验证字段必须是给定的日期之后的值对应的日期。
// 待验证字段必须是给定的日期之前的值对应的日期。
before:yyyy-mm-dd
alpha // 待验证字段只能由字母组成。
alpha_dash // 待验证字段可能包含字母、数字,短破折号(-)和下划线(_)。
alpha_num // 待验证字段只能由字母和数字组成。
array // 待验证字段必须是有效的 php 数组。
between:1,10 // 验证字段的大小必须在给定的 min 和 max 之间。字符串、数字、数组和文件的计算方式都使用size方法
confirmed // 验证字段必须具有匹配字段 foo_confirmation 
date // 根据 php strtotime 函数,验证的字段必须是有效的日期。
date_format:yyyy-mm-dd // 验证字段必须匹配给定的日期格式。
different:fieldname // 验证的字段值必须与字段 field 的值不同。
digits:value // 验证的字段必须为 numeric ,并且必须具有确切长度 _value_。
digits_between:min,max // 验证中的字段必须为数字,并且长度必须在给定的 min 和 max 之间。
boolean // 验证的字段必须可以转换为 boolean 类型。
email // 验证的字段必须符合 e-mail 地址格式。
// 验证的字段必须存在于给定的数据库表中。
exists:table,column
image // 验证的文件必须是图片 (jpeg, png, bmp, gif, svg, or webp)
in:foo,bar,... // 验证字段必须包含在给定的值列表中。
not_in:foo,bar,... // 验证字段不能包含在给定的值的列表中
integer // 验证的字段必须是整数。
numeric // 验证字段必须为数值。
ip // 验证的字段必须是 ip 地址。
max:value // 验证中的字段必须小于或等于 value。字符串、数字、数组或是文件大小的计算方式都用 size规则。
min:value // 验证中的字段必须小于或等于 value。同 max
mimes:jpeg,png // 验证的文件必须具有与列出的其中一个扩展名相对应的 mime 类型。
regex:[0-9] // 验证字段必须与给定的正则表达式匹配。
required // 验证的字段必须存在于输入数据中,而不是空。
required_if:field,value
required_with:foo,bar,...
required_with_all:foo,bar,...
required_without:foo,bar,...
required_without_all:foo,bar,...
same:field // 验证字段的值必须与给定字段的值相同。
size:value // 验证字段必须与给定值的大小一致。字符串(字符数),数字(数值),数组(count),文件(kb)
timezone // 验证字段必须为符合 timezone_identifiers_list 所定义的有效时区标识。
unique:table,column,except,idcolumn // 验证字段在给定的数据库表中必须是唯一的。
url // 验证的字段必须是有效的 url。

config

// config/app.php 里的 timezone 配置项
config::get('app.timezone')
config::get('app.timezone', 'default');
config::set('database.default', 'sqlite');
// config() 等同于 config facade
config()->get('app.timezone');
config('app.timezone', 'default');   // get
config(['database.default' => 'sqlite']); // set

route

route::get('foo', function(){});
route::get('foo', 'controllername@function');
route::controller('foo', 'foocontroller');

资源路由 

route::resource('posts','postscontroller');
// 资源路由器只允许指定动作通过
route::resource('photo', 'photocontroller',['only' => ['index', 'show']]);
route::resource('photo', 'photocontroller',['except' => ['update', 'destroy']]);
// 批量注册资源路由
route::resources(['foo' => 'foocontroller', 'bar' => 'barcontroller'])
route::resources(['foo' => 'foocontroller', 'bar' => 'barcontroller'], ['only' => ['index', 'show']])
route::resources(['foo' => 'foocontroller', 'bar' => 'barcontroller'], ['except' => ['update', 'destroy']])

触发错误 

app::abort(404);
$handler->missing(...) in errorserviceprovider::boot();
throw new notfoundhttpexception;

路由参数 

route::get('foo/{bar}', function($bar){});
route::get('foo/{bar?}', function($bar = 'bar'){});

http 请求方式

route::any('foo', function(){});
route::post('foo', function(){});
route::put('foo', function(){});
route::patch('foo', function(){});
route::delete('foo', function(){});
// restful 资源控制器
route::resource('foo', 'foocontroller');
// 为一个路由注册多种请求方式
route::match(['get', 'post'], '/', function(){});

安全路由 (tbd)

route::get('foo', array('https', function(){}));

路由约束

route::get('foo/{bar}', function($bar){})
        ->where('bar', '[0-9] ');
route::get('foo/{bar}/{baz}', function($bar, $baz){})
        ->where(array('bar' => '[0-9] ', 'baz' => '[a-za-z]'))
// 设置一个可跨路由使用的模式
 route::pattern('bar', '[0-9] ')

http 中间件 

// 为路由指定 middleware
route::get('admin/profile', ['middleware' => 'auth', function(){}]);
route::get('admin/profile', function(){})->middleware('auth');

命名路由

route::currentroutename();
route::get('foo/bar', array('as' => 'foobar', function(){}));
route::get('user/profile', [
    'as' => 'profile', 'uses' => 'usercontroller@showprofile'
]);
route::get('user/profile', 'usercontroller@showprofile')->name('profile');
$url = route('profile');
$redirect = redirect()->route('profile');

路由前缀

route::group(['prefix' => 'admin'], function()
{
    route::get('users', function(){
        return 'matches the "/admin/users" url';
    });
});

路由命名空间

// 此路由组将会传送 'foo\bar' 命名空间
route::group(array('namespace' => 'foo\bar'), function(){})

子域名路由

// {sub} 将在闭包中被忽略
route::group(array('domain' => '{sub}.example.com'), function(){});

model

基础使用

// 定义一个 eloquent 模型
class user extends model {}
// 生成一个 eloquent 模型
php artisan make:model user
// 生成一个 eloquent 模型的时候,顺便生成迁移文件
php artisan make:model user --migration or -m
// 生成一个 eloquent 模型的时候,顺便生成迁移文件、控制器(或资源控制器)
php artisan make:model user -mc[r]
// 指定一个自定义的数据表名称
class user extends model {
  protected $table = 'my_users';
}

more

//新增一条新数据
model::create(array('key' => 'value'));
// 通过属性找到第一条相匹配的数据或创造一条新数据
model::firstorcreate(array('key' => 'value'));
// 通过属性找到第一条相匹配的数据或实例化一条新数据
model::firstornew(array('key' => 'value'));
// 通过属性找到相匹配的数据并更新,如果不存在即创建
model::updateorcreate(array('search_key' => 'search_value'), array('key' => 'value'));
// 使用属性的数组来填充一个模型, 用的时候要小心「mass assignment」安全问题 !
model::fill($attributes);
model::destroy(1);
model::all();
model::find(1);
// 使用双主键进行查找
model::find(array('first', 'last'));
// 查找失败时抛出异常
model::findorfail(1);
// 使用双主键进行查找, 失败时抛出异常
model::findorfail(array('first', 'last'));
model::where('foo', '=', 'bar')->get();
model::where('foo', '=', 'bar')->first();
model::where('foo', '=', 'bar')->exists();
// 动态属性查找
model::wherefoo('bar')->first();
// 查找失败时抛出异常
model::where('foo', '=', 'bar')->firstorfail();
model::where('foo', '=', 'bar')->count();
model::where('foo', '=', 'bar')->delete();
// 输出原始的查询语句
model::where('foo', '=', 'bar')->tosql();
model::whereraw('foo = bar and cars = 2', array(20))->get();
model::on('connection-name')->find(1);
model::with('relation')->get();
model::all()->take(10);
model::all()->skip(10);
// 默认的 eloquent 排序是上升排序
model::all()->sortby('column');
model::all()->sortdesc('column');
// 查询 json 数据
model::where('options->language', 'en')->get(); # 字段是字符串
model::wherejsoncontains('options->languages', 'en')->get(); # 字段是数组
model::wherejsonlength('options->languages', 0)->get(); # 字段长度为 0
model::wherejsondoesntcontain('options->languages', 'en')->get(); # 字段是数组, 不包含

软删除

model::withtrashed()->where('cars', 2)->get();
// 在查询结果中包括带被软删除的模型
model::withtrashed()->where('cars', 2)->restore();
model::where('cars', 2)->forcedelete();
// 查找只带有软删除的模型
model::onlytrashed()->where('cars', 2)->get();

模型关联

// 一对一 - user::phone()
return $this->hasone('app\phone', 'foreign_key', 'local_key');
// 一对一 - phone::user(), 定义相对的关联
return $this->belongsto('app\user', 'foreign_key', 'other_key');
// 一对多 - post::comments()
return $this->hasmany('app\comment', 'foreign_key', 'local_key');
//  一对多 - comment::post()
return $this->belongsto('app\post', 'foreign_key', 'other_key');
// 多对多 - user::roles();
return $this->belongstomany('app\role', 'user_roles', 'user_id', 'role_id');
// 多对多 - role::users();
return $this->belongstomany('app\user');
// 多对多 - retrieving intermediate table columns
$role->pivot->created_at;
// 多对多 - 中介表字段
return $this->belongstomany('app\role')->withpivot('column1', 'column2');
// 多对多 - 自动维护 created_at 和 updated_at 时间戳
return $this->belongstomany('app\role')->withtimestamps();
// 远层一对多 - country::posts(), 一个 country 模型可能通过中介的 users
// 模型关联到多个 posts 模型(user::country_id)
return $this->hasmanythrough('app\post', 'app\user', 'country_id', 'user_id');
// 多态关联 - photo::imageable()
return $this->morphto();
// 多态关联 - staff::photos()
return $this->morphmany('app\photo', 'imageable');
// 多态关联 - product::photos()
return $this->morphmany('app\photo', 'imageable');
// 多态关联 - 在 appserviceprovider 中注册你的「多态对照表」
relation::morphmap([
    'post' => app\post::class,
    'comment' => app\comment::class,
]);
// 多态多对多关联 - 涉及数据库表: posts,videos,tags,taggables
// post::tags()
return $this->morphtomany('app\tag', 'taggable');
// video::tags()
return $this->morphtomany('app\tag', 'taggable');
// tag::posts()
return $this->morphedbymany('app\post', 'taggable');
// tag::videos()
return $this->morphedbymany('app\video', 'taggable');
// 查找关联
$user->posts()->where('active', 1)->get();
// 获取所有至少有一篇评论的文章...
$posts = app\post::has('comments')->get();
// 获取所有至少有三篇评论的文章...
$posts = post::has('comments', '>=', 3)->get();
// 获取所有至少有一篇评论被评分的文章...
$posts = post::has('comments.votes')->get();
// 获取所有至少有一篇评论相似于 foo% 的文章
$posts = post::wherehas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();
// 预加载
$books = app\book::with('author')->get();
$books = app\book::with('author', 'publisher')->get();
$books = app\book::with('author.contacts')->get();
// 延迟预加载
$books->load('author', 'publisher');
// 写入关联模型
$comment = new app\comment(['message' => 'a new comment.']);
$post->comments()->save($comment);
// save 与多对多关联
$post->comments()->savemany([
    new app\comment(['message' => 'a new comment.']),
    new app\comment(['message' => 'another comment.']),
]);
$post->comments()->create(['message' => 'a new comment.']);
// 更新「从属」关联
$user->account()->associate($account);
$user->save();
$user->account()->dissociate();
$user->save();
// 附加多对多关系
$user->roles()->attach($roleid);
$user->roles()->attach($roleid, ['expires' => $expires]);
// 从用户上移除单一身份...
$user->roles()->detach($roleid);
// 从用户上移除所有身份...
$user->roles()->detach();
$user->roles()->detach([1, 2, 3]);
$user->roles()->attach([1 => ['expires' => $expires], 2, 3]);
// 任何不在给定数组中的 ids 将会从中介表中被删除。
$user->roles()->sync([1, 2, 3]);
// 你也可以传递中介表上该 ids 额外的值:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);

事件

model::retrieved(function($model){});
model::creating(function($model){});
model::created(function($model){});
model::updating(function($model){});
model::updated(function($model){});
model::saving(function($model){});
model::saved(function($model){});
model::deleting(function($model){});
model::deleted(function($model){});
model::restoring(function($model){});
model::restored(function($model){});
model::observe(new fooobserver);

eloquent 配置信息

// 关闭模型插入或更新操作引发的 「mass assignment」异常
eloquent::unguard();
// 重新开启「mass assignment」异常抛出功能
eloquent::reguard();

cache

// 获取缓存对象,约等于 cache
cache()
// 注意 5.8 缓存单位为「秒」,之前版本为「分」
cache::put('key', 'value', $seconds);
// 未设置过期时间将永久有效
cache::put('key',  'value'); 
cache::add('key', 'value', $seconds);
cache::forever('key', 'value');
cache::sear('key', function(){ return 'value' });
cache::remember('key', $seconds, function(){ return 'value' });
cache::rememberforever('key', function(){ return 'value' });
cache::forget('key');
cache::has('key');
cache::get('key');
cache::get('key', 'default');
cache::get('key', function(){ return 'default'; });
// 取到数据之后再删除它
cache::pull('key'); 
// 清空所有缓存
cache::flush();
cache::increment('key');
cache::increment('key', $amount);
cache::decrement('key');
cache::decrement('key', $amount);
cache::tags('my-tag')->put('key','value', $seconds);
cache::tags('my-tag')->has('key');
cache::tags('my-tag')->get('key');
cache::tags(['people',  'artists'])->put('john',  $john,  $seconds);
cache::tags('my-tag')->forget('key');
cache::tags('my-tag')->flush();
cache::tags(['people',  'authors'])->flush();
cache::section('group')->put('key', $value);
cache::section('group')->get('key');
cache::section('group')->flush();
cache::tags(['people',  'artists'])->put('john',  $john,  $seconds);
// 辅助函数
cache('key');
cache(['key' => 'value'], $seconds);
cache(['key' => 'value'], now()->addminutes(10));
cache()->remember('users',  $seconds,  function() { return  user::all(); });
// 指定缓存存储
cache::store('file')->get('foo');
cache::store('redis')->put('name',  'jack',  600);  // 10 分钟
// 事件
'illuminate\cache\events\cachehit' => ['app\listeners\logcachehit',],
'illuminate\cache\events\cachemissed' => ['app\listeners\logcachemissed',],
'illuminate\cache\events\keyforgotten' => ['app\listeners\logkeyforgotten',],
'illuminate\cache\events\keywritten' => ['app\listeners\logkeywritten',],

cookie

// 等于 cookie
cookie();
request()->cookie('name');
cookie::get('key');
cookie::get('key', 'default');
// 创建一个永久有效的 cookie
cookie::forever('key', 'value');
// 创建一个 n 分钟有效的 cookie
cookie::make('key', 'value', 'minutes');
cookie('key', 'value', 'minutes');
// 在回应之前先积累 cookie,回应时统一返回
cookie::queue('key', 'value', 'minutes');
// 移除 cookie
cookie::forget('key');
// 从 response 发送一个 cookie
$response = response::make('hello world');
$response->withcookie(cookie::make('name', 'value', $minutes));
// 设置未加密 cookie app/http/middleware/encryptcookies.php
encryptcookies->except = ['cookie_name_1'];

request

//获取请求参数 form-data 与 raw 请求类型
request()->input();
// url: http://xx.com/aa/bb
request::;
// 路径: /aa/bb
request::path();
// 获取请求 uri: /aa/bb/?c=d
request::getrequesturi();
// 返回用户的 ip
request::ip();
// 获取 uri: http://xx.com/aa/bb/?c=d
request::geturi();
// 获取查询字符串: c=d
request::getquerystring();
// 获取请求端口 (例如 80, 443 等等)
request::getport();
// 判断当前请求的 uri 是否可被匹配
request::is('foo/*');
// 获取 uri 的分段值 (索引从 1 开始)
request::segment(1);
// 从请求中取回头部信息
request::header('content-type');
// 从请求中取回服务器变量
request::server('path_info');
// 判断请求是否是 ajax 请求
request::ajax();
// 判断请求是否使用 https
request::secure();
// 获取请求方法
request::method();
// 判断请求方法是否是指定类型的
request::ismethod('post');
// 获取原始的 post 数据
request::instance()->getcontent();
// 获取请求要求返回的格式
request::format();
// 判断 http content-type 头部信息是否包含 */json
request::isjson();
// 判断 http accept 头部信息是否为 application/json
request::wantsjson();

redirect

return redirect::to('foo/bar');
return redirect::to('foo/bar')->with('key', 'value');
return redirect::to('foo/bar')->withinput(input::get());
return redirect::to('foo/bar')->withinput(input::except('password'));
return redirect::to('foo/bar')->witherrors($validator);
// 重定向到之前的请求
return redirect::back();
// 重定向到命名路由(根据命名路由算出 url)
return redirect::route('foobar');
return redirect::route('foobar', array('value'));
return redirect::route('foobar', array('key' => 'value'));
// 重定向到控制器动作(根据控制器动作算出 url)
return redirect::action('foocontroller@index');
return redirect::action('foocontroller@baz', array('value'));
return redirect::action('foocontroller@baz', array('key' => 'value'));
// 跳转到目的地址,如果没有设置则使用默认值 foo/bar
return redirect::intended('foo/bar');

mail

mail::send('email.view', $data, function($message){});
mail::send(array('html.view', 'text.view'), $data, $callback);
mail::queue('email.view', $data, function($message){});
mail::queueon('queue-name', 'email.view', $data, $callback);
mail::later(5, 'email.view', $data, function($message){});
// 临时将发送邮件请求写入 log,方便测试
 mail::pretend();

消息

// 这些都能在 $message 实例中使用, 并可传入到 mail::send() 或 mail::queue()
$message->from('[email protected]', 'mr. example');
$message->sender('[email protected]', 'mr. example');
$message->returnpath('[email protected]');
$message->to('[email protected]', 'mr. example');
$message->cc('[email protected]', 'mr. example');
$message->bcc('[email protected]', 'mr. example');
$message->replyto('[email protected]', 'mr. example');
$message->subject('welcome to the jungle');
$message->priority(2);
$message->attach('foo\bar.txt', $options);
// 使用内存数据作为附件
$message->attachdata('bar', 'data name', $options);
// 附带文件,并返回 cid
$message->embed('foo\bar.txt');
$message->embeddata('foo', 'data name', $options);
// 获取底层的 swift message 对象
$message->getswiftmessage();

view

view::make('path/to/view');
view::make('foo/bar')->with('key', 'value');
view::make('foo/bar')->withkey('value');
view::make('foo/bar', array('key' => 'value'));
view::exists('foo/bar');
// 跨视图共享变量
view::share('key', 'value');
// 视图嵌套
view::make('foo/bar')->nest('name', 'foo/baz', $data);
// 注册一个视图构造器
view::composer('viewname', function($view){});
// 注册多个视图到一个视图构造器中
view::composer(array('view1', 'view2'), function($view){});
// 注册一个视图构造器类
view::composer('viewname', 'foocomposer');
view::creator('viewname', function($view){});

blade

// 输出内容,被转义过的
{{ $var }}
// 输出未转义内容
{!! $var !!}
{{-- blade 注释,不会被输出到页面中 --}}
// 三元表达式的简写,以下相当于「isset($name) ? $name : 'default'」
{{ $name ?? 'default' }}
// 等同 echo json_encode($array);
@json($array);
// 禁用 html 实体双重编码
blade::withoutdoubleencoding();
// 书写 php 代码
@php 
@endphp
@csrf // csrf 域
@method('put') // html 表单伪造方法 _method
// 服务容器注入,后调用 {{ $metrics->monthlyrevenue() }}
@inject('metrics', 'app\services\metricsservice')

包含和继承

// 扩展布局模板
@extends('layout.name')
// 区块占位
@yield('name')
// 第一种、直接填入扩展内容
@section('title',  'page title')
// 第二种、实现命名为 name 的区块(yield 占位的地方)
@section('sidebar')
    // 继承父模板内容
    @parent
@endsection
// 可继承内容区块
@section('sidebar')
@show
// 继承父模板内容(@show 的区块内容)
@parent
// 包含子视图
@include('view.name')
// 包含子视图,并传参
@include('view.name', ['key' => 'value']);
@includeif('view.name',  ['some'  =>  'data'])
@includewhen($boolean,  'view.name',  ['some'  =>  'data'])
// 包含给定视图数组中第一个存在的视图
@includefirst(['custom.admin',  'admin'],  ['some'  =>  'data'])
// 加载本地化语句
@lang('messages.name')
@choice('messages.name', 1);
// 检查片断是否存在
@hassection('navigation')
        @yield('navigation')
@endif
// 迭代 jobs 数组并包含
@each('view.name',  $jobs,  'job')
@each('view.name',  $jobs,  'job',  'view.empty')
// 堆栈
@stack('scripts')
@push('scripts')
    
@endpush
// 栈顶插入
@prepend('scripts')
@endprepend
// 组件
@component('alert', ['foo' => 'bar'])
    @slot('title')
    @endslot
@endcomponent
// 注册别名 @alert(['type' => 'danger'])...@endalert
blade::component('components.alert',  'alert');

条件语句

@if (count($records) === 1)
@elseif  (count($records) > 1)
@else
@endif
// 登录情况下
@unless (auth::check())
@endunless
// $records 被定义且不是  null...
@isset($records)
@endisset
// $records 为空...
@empty($records)
@endempty
// 此用户身份已验证...
@auth // 或 @auth('admin')
@endauth
// 此用户身份未验证...
@guest // 或 @guest('admin')
@endguest
@switch($i)
    @case(1)
        @break
    @default
        // 默认
@endswitch

循环

// for 循环
@for ($i = 0; $i < 10; $i  )
@endfor
// foreach 迭代
@foreach ($users as $user)
@endforeach
// 迭代如果为空的话
@forelse ($users as $user)
@empty
@endforelse
// while 循环
@while (true)
@endwhile
// 终结循环
@continue
@continue($user->type  ==  1) // 带条件
// 跳过本次迭代
@break
@break($user->number  ==  5) // 带条件
// 循环变量
$loop->index        // 当前迭代的索引(从 0 开始计数)。
$loop->iteration    // 当前循环迭代 (从 1 开始计算)。
$loop->remaining    // 循环中剩余迭代的数量。
$loop->count        // 被迭代的数组元素的总数。
$loop->first        // 是否为循环的第一次迭代。
$loop->last         // 是否为循环的最后一次迭代。
$loop->depth        // 当前迭代的嵌套深度级数。
$loop->parent       // 嵌套循环中,父循环的循环变量

javascript 代码

// js 框架,保留双大括号,以下会编译为 {{ name }}
@{{ name }}
// 大段 javascript 变量,verbatim 里模板引擎将不解析
@verbatim
        hello, {{ javascriptvariablename }}.
@endverbatim

string

// 将 utf-8 的值直译为 ascii 类型的值
str::ascii($value)
str::camel($value)
str::contains($haystack, $needle)
str::endswith($haystack, $needles)
str::finish($value, $cap)
str::is($pattern, $value)
str::length($value)
str::limit($value, $limit = 100, $end = '...')
str::lower($value)
str::words($value, $words = 100, $end = '...')
str::plural($value, $count = 2)
// 生成更加真实的 "随机" 字母数字字符串.
str::random($length = 16)
// 生成一个 "随机" 字母数字字符串.
str::quickrandom($length = 16)
str::upper($value)
str::title($value)
str::singular($value)
str::slug($title, $separator = '-')
str::snake($value, $delimiter = '_')
str::startswith($haystack, $needles)
str::studly($value)
str::macro($name, $macro)

collection

// 创建集合
collect([1, 2, 3]);
// 返回该集合所代表的底层数组:
$collection->all();
// 返回集合中所有项目的平均值:
collect([1, 1, 2, 4])->avg() // 2
$collection->average();
// 将集合拆成多个给定大小的较小集合:
collect([1, 2, 3, 4, 5])->chunk(2); // [[1,2], [3,4], [5]]
// 将多个数组组成的集合折成单一数组集合:
collect([[1],  [4,  5]])->collapse(); // [1, 4, 5]
// 将一个集合的值作为键,再将另一个集合作为值合并成一个集合
collect(['name', 'age'])->combine(['george', 29]);
// 将给定的 数组 或集合值追加到集合的末尾
collect(['php'])->concat(['laravel']); // ['php', 'laravel']
// 用来判断该集合是否含有指定的项目:
collect(['name' => 'desk'])->contains('desk'); // true
collect(['name' => 'desk'])->contains('name',  'desk'); // true
// 返回该集合内的项目总数:
$collection->count();
// 交叉连接指定数组或集合的值,返回所有可能排列的笛卡尔积
collect([1, 2])->crossjoin(['a', 'b']); // [[1, 'a'],[1, 'b'],[2, 'a'],[2, 'b']]
// dd($collection) 的另一个写法
collect(['john doe', 'jane doe'])->dd();
// 返回原集合中存在而指定集合中不存在的值
collect([1,  2,  3])->diff([2, 4]); // [1, 3]
// 返回原集合不存在与指定集合的键 / 值对
collect(['color' => 'orange', 'remain' =>  6])->diffassoc(['color' => 'yellow', 'remain' => 6, 'used' => 6]);  // ['color' => 'orange']
// 返回原集合中存在而指定集合中不存在键所对应的键 / 值对
collect(['one' => 10, 'two' => 20])->diffkeys(['two' => 2, 'four' => 4]); // ['one' => 10]
// 类似于 dd() 方法,但是不会中断
collect(['john doe', 'jane doe'])->dump();
// 遍历集合中的项目,并将之传入给定的回调函数:
$collection = $collection->each(function ($item, $key) {});
// 验证集合中的每一个元素是否通过指定的条件测试
collect([1,  2])->every(function  ($value,  $key)  { return $value > 1; }); // false
// 返回集合中排除指定键的所有项目:
$collection->except(['price', 'discount']);
// 以给定的回调函数筛选集合,只留下那些通过判断测试的项目:
$filtered = $collection->filter(function ($item) {
    return $item > 2;
});
// 返回集合中,第一个通过给定测试的元素:
collect([1, 2, 3, 4])->first(function ($key, $value) {
    return $value > 2;
});
// 将多维集合转为一维集合:
$flattened = $collection->flatten();
// 将集合中的键和对应的数值进行互换:
$flipped = $collection->flip();
// 以键自集合移除掉一个项目:
$collection->forget('name');
// 返回含有可以用来在给定页码显示项目的新集合:
$chunk = $collection->forpage(2, 3);
// 返回给定键的项目。如果该键不存在,则返回 null:
$value = $collection->get('name');
// 根据给定的键替集合内的项目分组:
$grouped = $collection->groupby('account_id');
// 用来确认集合中是否含有给定的键:
$collection->has('email');
// 用来连接集合中的项目
$collection->implode('product', ', ');
// 移除任何给定数组或集合内所没有的数值:
$intersect = $collection->intersect(['desk', 'chair', 'bookcase']);
// 假如集合是空的,isempty 方法会返回 true:
collect([])->isempty();
// 以给定键的值作为集合项目的键:
$keyed = $collection->keyby('product_id');
// 传入回调函数,该函数会返回集合的键的值:
$keyed = $collection->keyby(function ($item) {
    return strtoupper($item['product_id']);
});
// 返回该集合所有的键:
$keys = $collection->keys();
// 返回集合中,最后一个通过给定测试的元素:
$collection->last();
// 遍历整个集合并将每一个数值传入给定的回调函数:
$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});
// 返回给定键的最大值:
$max = collect([['foo' => 10], ['foo' => 20]])->max('foo');
$max = collect([1, 2, 3, 4, 5])->max();
// 将合并指定的数组或集合到原集合:
$merged = $collection->merge(['price' => 100, 'discount' => false]);
// 返回给定键的最小值:
$min = collect([['foo' => 10], ['foo' => 20]])->min('foo');
$min = collect([1, 2, 3, 4, 5])->min();
// 返回集合中指定键的所有项目:
$filtered = $collection->only(['product_id', 'name']);
// 获取所有集合中给定键的值:
$plucked = $collection->pluck('name');
// 移除并返回集合最后一个项目:
$collection->pop();
// 在集合前面增加一个项目:
$collection->prepend(0);
// 传递第二个参数来设置前置项目的键:
$collection->prepend(0, 'zero');
// 以键从集合中移除并返回一个项目:
$collection->pull('name');
// 附加一个项目到集合后面:
$collection->push(5);
// put 在集合内设置一个给定键和数值:
$collection->put('price', 100);
// 从集合中随机返回一个项目:
$collection->random();
// 传入一个整数到 random。如果该整数大于 1,则会返回一个集合:
$random = $collection->random(3);
// 会将每次迭代的结果传入到下一次迭代:
$total = $collection->reduce(function ($carry, $item) {
    return $carry  $item;
});
// 以给定的回调函数筛选集合:
$filtered = $collection->reject(function ($item) {
    return $item > 2;
});
// 反转集合内项目的顺序:
$reversed = $collection->reverse();
// 在集合内搜索给定的数值并返回找到的键:
$collection->search(4);
// 移除并返回集合的第一个项目:
$collection->shift();
// 随机排序集合的项目:
$shuffled = $collection->shuffle();
// 返回集合从给定索引开始的一部分切片:
$slice = $collection->slice(4);
// 对集合排序:
$sorted = $collection->sort();
// 以给定的键排序集合:
$sorted = $collection->sortby('price');
// 移除并返回从指定的索引开始的一小切片项目:
$chunk = $collection->splice(2);
// 返回集合内所有项目的总和:
collect([1, 2, 3, 4, 5])->sum();
// 返回有着指定数量项目的集合:
$chunk = $collection->take(3);
// 将集合转换成纯 php 数组:
$collection->toarray();
// 将集合转换成 json:
$collection->tojson();
// 遍历集合并对集合内每一个项目调用给定的回调函数:
$collection->transform(function ($item, $key) {
    return $item * 2;
});
// 返回集合中所有唯一的项目:
$unique = $collection->unique();
// 返回键重设为连续整数的的新集合:
$values = $collection->values();
// 以一对给定的键/数值筛选集合:
$filtered = $collection->where('price', 100);
// 将集合与给定数组同样索引的值合并在一起:
$zipped = $collection->zip([100, 200]);
//把集合放到回调参数中并返回回调的结果:
collect([1, 2, 3])->pipe(function ($collection) {
    return $collection->sum();
});//6

storage

// 写入文件
storage::put('avatars/1', $filecontents);
// 指定磁盘
storage::disk('local')->put('file.txt', 'contents');
storage::get('file.jpg');
storage::exists('file.jpg');
storage::download('file.jpg',  $name,  $headers);
storage::;
storage::temporary->addminutes(5));
storage::size('file.jpg');
storage::lastmodified('file.jpg');
// 自动为文件名生成唯一的id...  
storage::putfile('photos',  new  file('/path/to/photo'));
// 手动指定文件名...  
storage::putfileas('photos', new  file('/path/to/photo'), 'photo.jpg');
storage::prepend('file.log', 'prepended text');
storage::append('file.log', 'appended text');
storage::copy('old/file.jpg', 'new/file.jpg');
storage::move('old/file.jpg', 'new/file.jpg');
storage::putfileas('avatars', $request->file('avatar'), auth::id());
// 「可见性」是对多个平台的文件权限的抽象
storage::getvisibility('file.jpg');
storage::setvisibility('file.jpg',  'public')
storage::delete('file.jpg');
storage::delete(['file.jpg',  'file2.jpg']);
// 获取目录下的所有的文件
storage::files($directory);
storage::allfiles($directory);
// 获取目录下的所有目录
storage::directories($directory);
storage::alldirectories($directory);
// 创建目录
storage::makedirectory($directory);
// 删除目录
storage::deletedirectory($directory);
网站地图