🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 辅助函数 - [简介](#introduction) - [可用方法](#available-methods) <a name="introduction"></a> ## 简介 Laravel 包含各种各样的「全局」PHP辅助函数,框架本身也大量的使用了这些功能函数;如果你觉的方便,你可以在你的应用中任意使用这些函数 <a name="available-methods"></a> ## 可用方法 <style> .collection-method-list > p { column-count: 3; -moz-column-count: 3; -webkit-column-count: 3; column-gap: 2em; -moz-column-gap: 2em; -webkit-column-gap: 2em; } .collection-method-list a { display: block; } </style> ### 数组 & 对象 <div class="collection-method-list" markdown="1"> [Arr::add](#method-array-add) [Arr::collapse](#method-array-collapse) [Arr::divide](#method-array-divide) [Arr::dot](#method-array-dot) [Arr::except](#method-array-except) [Arr::first](#method-array-first) [Arr::flatten](#method-array-flatten) [Arr::forget](#method-array-forget) [Arr::get](#method-array-get) [Arr::has](#method-array-has) [Arr::last](#method-array-last) [Arr::only](#method-array-only) [Arr::pluck](#method-array-pluck) [Arr::prepend](#method-array-prepend) [Arr::pull](#method-array-pull) [Arr::random](#method-array-random) [Arr::set](#method-array-set) [Arr::sort](#method-array-sort) [Arr::sortRecursive](#method-array-sort-recursive) [Arr::where](#method-array-where) [Arr::wrap](#method-array-wrap) [data_fill](#method-data-fill) [data_get](#method-data-get) [data_set](#method-data-set) [head](#method-head) [last](#method-last) </div> ### 路径 <div class="collection-method-list" markdown="1"> [app_path](#method-app-path) [base_path](#method-base-path) [config_path](#method-config-path) [database_path](#method-database-path) [mix](#method-mix) [public_path](#method-public-path) [resource_path](#method-resource-path) [storage_path](#method-storage-path) </div> ### 字符串 <div class="collection-method-list" markdown="1"> [\__](#method-__) [Str::camel](#method-camel-case) [class_basename](#method-class-basename) [e](#method-e) [Str::endsWith](#method-ends-with) [Str::kebab](#method-kebab-case) [preg_replace_array](#method-preg-replace-array) [Str::snake](#method-snake-case) [Str::startsWith](#method-starts-with) [Str::after](#method-str-after) [Str::before](#method-str-before) [Str::contains](#method-str-contains) [Str::finish](#method-str-finish) [Str::is](#method-str-is) [Str::limit](#method-str-limit) [Str::orderedUuid](#method-str-ordered-uuid) [Str::plural](#method-str-plural) [Str::random](#method-str-random) [Str::replaceArray](#method-str-replace-array) [Str::replaceFirst](#method-str-replace-first) [Str::replaceLast](#method-str-replace-last) [Str::singular](#method-str-singular) [Str::slug](#method-str-slug) [Str::start](#method-str-start) [Str::studly](#method-studly-case) [Str::title](#method-title-case) [trans](#method-trans) [trans_choice](#method-trans-choice) [Str::uuid](#method-str-uuid) </div> ### URLs <div class="collection-method-list" markdown="1"> [action](#method-action) [asset](#method-asset) [secure_asset](#method-secure-asset) [route](#method-route) [secure_url](#method-secure-url) [url](#method-url) </div> ### 其他 <div class="collection-method-list" markdown="1"> [abort](#method-abort) [abort_if](#method-abort-if) [abort_unless](#method-abort-unless) [app](#method-app) [auth](#method-auth) [back](#method-back) [bcrypt](#method-bcrypt) [blank](#method-blank) [broadcast](#method-broadcast) [cache](#method-cache) [class_uses_recursive](#method-class-uses-recursive) [collect](#method-collect) [config](#method-config) [cookie](#method-cookie) [csrf_field](#method-csrf-field) [csrf_token](#method-csrf-token) [dd](#method-dd) [decrypt](#method-decrypt) [dispatch](#method-dispatch) [dispatch_now](#method-dispatch-now) [dump](#method-dump) [encrypt](#method-encrypt) [env](#method-env) [event](#method-event) [factory](#method-factory) [filled](#method-filled) [info](#method-info) [logger](#method-logger) [method_field](#method-method-field) [now](#method-now) [old](#method-old) [optional](#method-optional) [policy](#method-policy) [redirect](#method-redirect) [report](#method-report) [request](#method-request) [rescue](#method-rescue) [resolve](#method-resolve) [response](#method-response) [retry](#method-retry) [session](#method-session) [tap](#method-tap) [today](#method-today) [throw_if](#method-throw-if) [throw_unless](#method-throw-unless) [trait_uses_recursive](#method-trait-uses-recursive) [transform](#method-transform) [validator](#method-validator) [value](#method-value) [view](#method-view) [with](#method-with) </div> <a name="method-listing"></a> ## 方法列表 <style> #collection-method code { font-size: 14px; } #collection-method:not(.first-collection-method) { margin-top: 50px; } </style> <a name="arrays"></a> ## 数组 & 对象 <a name="method-array-add"></a> #### `Arr::add()` {#collection-method .first-collection-method} 如果给定的键不存在数组中,那么 `Arr::add` 函数将会把给定的键/值对添加到数组中: use Illuminate\Support\Arr; $array = Arr::add(['name' => 'Desk'], 'price', 100); // ['name' => 'Desk', 'price' => 100] <a name="method-array-collapse"></a> #### `Arr::collapse()` {#collection-method} `Arr::collapse` 函数将多个数组合并为一个数组: use Illuminate\Support\Arr; $array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); // [1, 2, 3, 4, 5, 6, 7, 8, 9] <a name="method-array-divide"></a> #### `Arr::divide()` {#collection-method} `Arr::divide` 函数返回一个二维数组,一个值包含原始数组的键,另一个值包含原始数组的值: use Illuminate\Support\Arr; [$keys, $values] = Arr::divide(['name' => 'Desk']); // $keys: ['name'] 多维数组中的第0个值 // $values: ['Desk'] 多维数组中的第1个值 <a name="method-array-dot"></a> #### `Arr::dot()` {#collection-method} `Arr::dot` 函数将多维数组中所有的键平铺到一维数组中,新数组使用「.」符号表示层级包含关系: use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; $flattened = Arr::dot($array); // ['products.desk.price' => 100] <a name="method-array-except"></a> #### `Arr::except()` {#collection-method} `Arr::except` 函数从数组中删除给定的键/值对: use Illuminate\Support\Arr; $array = ['name' => 'Desk', 'price' => 100]; $filtered = Arr::except($array, ['price']); // ['name' => 'Desk'] <a name="method-array-first"></a> #### `Arr::first()` {#collection-method} `Arr::first` 函数返回数组中通过指定测试的第一个元素: use Illuminate\Support\Arr; $array = [100, 200, 300]; $first = Arr::first($array, function ($value, $key) { return $value >= 150; }); // 200 将默认值作为第三个参数传递给该方法, 如果数组中没有值通过测试,则返回默认值: use Illuminate\Support\Arr; $first = Arr::first($array, $callback, $default); <a name="method-array-flatten"></a> #### `Arr::flatten()` {#collection-method} `Arr::flatten` 函数将多维数组中数组的值取出平铺为一维数组: use Illuminate\Support\Arr; $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; $flattened = Arr::flatten($array); // ['Joe', 'PHP', 'Ruby'] <a name="method-array-forget"></a> #### `Arr::forget()` {#collection-method} `Arr::forget` 函数使用「.」符号从深度嵌套的数组中删除给定的键/值对: use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; Arr::forget($array, 'products.desk'); // ['products' => []] <a name="method-array-get"></a> #### `Arr::get()` {#collection-method} `Arr::get` 函数使用「.」符号从深度嵌套的数组中根据指定键检索值: use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; $price = Arr::get($array, 'products.desk.price'); // 100 `Arr::get` 函数也接受一个默认值,如果没有找到特定的键,将返回默认值: use Illuminate\Support\Arr; $discount = Arr::get($array, 'products.desk.discount', 0); // 0 <a name="method-array-has"></a> #### `Arr::has()` {#collection-method} `Arr::has` 函数使用「.」符号查找数组中是否存在指定的一个或多个键: use Illuminate\Support\Arr; $array = ['product' => ['name' => 'Desk', 'price' => 100]]; $contains = Arr::has($array, 'product.name'); // true $contains = Arr::has($array, ['product.price', 'product.discount']); // false <a name="method-array-last"></a> #### `Arr::last()` {#collection-method} `Arr::last` 函数返回数组中通过指定测试的最后一个元素: use Illuminate\Support\Arr; $array = [100, 200, 300, 110]; $last = Arr::last($array, function ($value, $key) { return $value >= 150; }); // 300 将默认值作为第三个参数传递给该方法,如果没有值通过指定测试,则返回该默认值: use Illuminate\Support\Arr; $last = Arr::last($array, $callback, $default); <a name="method-array-only"></a> #### `Arr::only()` {#collection-method} `Arr::only` 函数只返回给定数组中指定的键/值对: use Illuminate\Support\Arr; $array = ['name' => 'Desk', 'price' => 100, 'orders' => 10]; $slice = Arr::only($array, ['name', 'price']); // ['name' => 'Desk', 'price' => 100] <a name="method-array-pluck"></a> #### `Arr::pluck()` {#collection-method} `Arr::pluck` 函数从数组中检索给定键的所有值: use Illuminate\Support\Arr; $array = [ ['developer' => ['id' => 1, 'name' => 'Taylor']], ['developer' => ['id' => 2, 'name' => 'Abigail']], ]; $names = Arr::pluck($array, 'developer.name'); // ['Taylor', 'Abigail'] 你也可以指定获取的结果的键: use Illuminate\Support\Arr; $names = Arr::pluck($array, 'developer.name', 'developer.id'); // [1 => 'Taylor', 2 => 'Abigail'] <a name="method-array-prepend"></a> #### `Arr::prepend()` {#collection-method} `Arr::prepend` 函数将一个值插入到数组的开始位置: use Illuminate\Support\Arr; $array = ['one', 'two', 'three', 'four']; $array = Arr::prepend($array, 'zero'); // ['zero', 'one', 'two', 'three', 'four'] 如果需要,你可以指定你插入值的键: use Illuminate\Support\Arr; $array = ['price' => 100]; $array = Arr::prepend($array, 'Desk', 'name'); // ['name' => 'Desk', 'price' => 100] <a name="method-array-pull"></a> #### `Arr::pull()` {#collection-method} `Arr::pull` 函数从数组中返回指定键的值并删除此键/值对: use Illuminate\Support\Arr; $array = ['name' => 'Desk', 'price' => 100]; $name = Arr::pull($array, 'name'); // $name: Desk // $array: ['price' => 100] 默认值可以作为第三个参数传递给该方法,如果键不存在,则返回该值: use Illuminate\Support\Arr; $value = Arr::pull($array, $key, $default); <a name="method-array-random"></a> #### `Arr::random()` {#collection-method} `Arr::random` 函数从数组中随机返回一个值: use Illuminate\Support\Arr; $array = [1, 2, 3, 4, 5]; $random = Arr::random($array); // 4 - (随机检索) 你也可以将返回值的数量作为可选的第二个参数传递给该方法,请注意,提供这个参数会返回一个数组,即便是你只需要一项: use Illuminate\Support\Arr; $items = Arr::random($array, 2); // [2, 5] - (随机检索) <a name="method-array-set"></a> #### `Arr::set()` {#collection-method} `Arr::set` 函数使用「.」符号在多维数组中设置指定键的值: use Illuminate\Support\Arr; $array = ['products' => ['desk' => ['price' => 100]]]; Arr::set($array, 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 200]]] <a name="method-array-sort"></a> #### `Arr::sort()` {#collection-method} `Arr::sort` 函数根据数组的值对数组进行排序: use Illuminate\Support\Arr; $array = ['Desk', 'Table', 'Chair']; $sorted = Arr::sort($array); // ['Chair', 'Desk', 'Table'] 你也可以根据给定闭包返回的结果对数组进行排序: use Illuminate\Support\Arr; $array = [ ['name' => 'Desk'], ['name' => 'Table'], ['name' => 'Chair'], ]; $sorted = array_values(Arr::sort($array, function ($value) { return $value['name']; })); /* [ ['name' => 'Chair'], ['name' => 'Desk'], ['name' => 'Table'], ] */ <a name="method-array-sort-recursive"></a> #### `Arr::sortRecursive()` {#collection-method} `Arr::sortRecursive` 函数使用 `sort` 函数对数组进行递归排序: use Illuminate\Support\Arr; $array = [ ['Roman', 'Taylor', 'Li'], ['PHP', 'Ruby', 'JavaScript'], ['one' => 1, 'two' => 2, 'three' => 3], ]; $sorted = Arr::sortRecursive($array); /* [ ['JavaScript', 'PHP', 'Ruby'], ['one' => 1, 'three' => 3, 'two' => 2], ['Li', 'Roman', 'Taylor'], ] */ <a name="method-array-where"></a> #### `Arr::where()` {#collection-method} `Arr::where` 函数使用给定闭包返回的结果过滤数组: use Illuminate\Support\Arr; $array = [100, '200', 300, '400', 500]; $filtered = Arr::where($array, function ($value, $key) { return is_string($value); }); // [1 => '200', 3 => '400'] <a name="method-array-wrap"></a> #### `Arr::wrap()` {#collection-method} `Arr::wrap` 函数将给定的值变为一个数组, 如果给定的值已经是数组,则不改变: use Illuminate\Support\Arr; $string = 'Laravel'; $array = Arr::wrap($string); // ['Laravel'] 如果给定的值是空,则返回一个空数组: use Illuminate\Support\Arr; $nothing = null; $array = Arr::wrap($nothing); // [] <a name="method-data-fill"></a> #### `data_fill()` {#collection-method} `data_fill` 函数使用「.」符号在多维数组或对象内设置缺省值: $data = ['products' => ['desk' => ['price' => 100]]]; data_fill($data, 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 100]]] data_fill($data, 'products.desk.discount', 10); // ['products' => ['desk' => ['price' => 100, 'discount' => 10]]] 这个函数还接受星号「*」作为通配符,相应的填充目标: $data = [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2'], ], ]; data_fill($data, 'products.*.price', 200); /* [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2', 'price' => 200], ], ] */ <a name="method-data-get"></a> #### `data_get()` {#collection-method} `data_get` 函数使用「.」符号从多维数组或对象中检索值 $data = ['products' => ['desk' => ['price' => 100]]]; $price = data_get($data, 'products.desk.price'); // 100 `data_get` 函数也可以接收一个默认值, 如果找不到指定的键,则返回默认值: $discount = data_get($data, 'products.desk.discount', 0); // 0 这个函数还接受「*」作为通配符,它可以匹配数组或对象的任何键: $data = [ 'product-one' => ['name' => 'Desk 1', 'price' => 100], 'product-two' => ['name' => 'Desk 2', 'price' => 150], ]; data_get($data, '*.name'); // ['Desk 1', 'Desk 2']; <a name="method-data-set"></a> #### `data_set()` {#collection-method} `data_set` 函数使用「.」符号在多维数组或对象中设置一个值: $data = ['products' => ['desk' => ['price' => 100]]]; data_set($data, 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 200]]] 该函数也可以接收「*」通配符,相应的在指定键上设置值: $data = [ 'products' => [ ['name' => 'Desk 1', 'price' => 100], ['name' => 'Desk 2', 'price' => 150], ], ]; data_set($data, 'products.*.price', 200); /* [ 'products' => [ ['name' => 'Desk 1', 'price' => 200], ['name' => 'Desk 2', 'price' => 200], ], ] */ 默认情况下, 所有现有值都会被覆盖, 如果你只希望设置不存在的值,你可以选择 `false` 作为第四个参数传递给该方法: $data = ['products' => ['desk' => ['price' => 100]]]; data_set($data, 'products.desk.price', 200, false); // ['products' => ['desk' => ['price' => 100]]] <a name="method-head"></a> #### `head()` {#collection-method} `head` 函数返回给定数组中的第一个元素: $array = [100, 200, 300]; $first = head($array); // 100 <a name="method-last"></a> #### `last()` {#collection-method} `last` 函数返回给定数组中的最后一个元素: $array = [100, 200, 300]; $last = last($array); // 300 <a name="paths"></a> ## 路径 <a name="method-app-path"></a> #### `app_path()` {#collection-method} `app_path` 函数返回 `app` 目录的完整路径.你也可以使用 `app_path` 函数来设置应用程序 `app` 目录的完整路径: $path = app_path(); $path = app_path('Http/Controllers/Controller.php'); <a name="method-base-path"></a> #### `base_path()` {#collection-method} `base_path` 函数返回项目根目录的完整路径.你也可以使用 `base_path` 函数设置项目根目录的完整路径: $path = base_path(); $path = base_path('vendor/bin'); <a name="method-config-path"></a> #### `config_path()` {#collection-method} `config_path` 函数返回 `config`目录的完整路径.你也可以使用 `config_path` 函数设置应用程序 `config` 目录中给定文件的完整路径: $path = config_path(); $path = config_path('app.php'); <a name="method-database-path"></a> #### `database_path()` {#collection-method} `database_path` 函数返回 `database` 目录的完整路径.你也可以使用 `database_path` 函数来设置 `database` 目录中给定文件的完整路径: $path = database_path(); $path = database_path('factories/UserFactory.php'); <a name="method-mix"></a> #### `mix()` {#collection-method} `mix` 函数返回 [版本化 Mix 文件](/docs/{{version}}/mix) 的路径: $path = mix('css/app.css'); <a name="method-public-path"></a> #### `public_path()` {#collection-method} `public_path` 函数返回 `public` 目录的完整路径.你也可以使用 `public_path` 函数来生成 `public` 目录中给定文件的完整路径: $path = public_path(); $path = public_path('css/app.css'); <a name="method-resource-path"></a> #### `resource_path()` {#collection-method} `resource_path` 函数返回 `resources` 目录的完整路径.你也可以使用 `resource_path` 函数来生成资源文件中给定文件的完整路径 $path = resource_path(); $path = resource_path('sass/app.scss'); <a name="method-storage-path"></a> #### `storage_path()` {#collection-method} `storage_path` 函数返回 `storage` 目录的完整路径.你也可以使用 `storage_path` 函数来设置存储目录下指定文件的完整路径 : $path = storage_path(); $path = storage_path('app/file.txt'); <a name="strings"></a> ## 字符串 <a name="method-__"></a> #### `__()` {#collection-method} `__` 函数使用你的[本地化文件](/docs/{{version}}/localization)来翻译给定的翻译字符串或翻译键: echo __('Welcome to our application'); echo __('messages.welcome'); 如果指定的翻译字符串或翻译键不存在, `__` 函数将返回给定的值.所以,按照上面的例子,如果翻译键 `messages.welcome` 不存在, `__` 函数会将其直接返回. <a name="method-camel-case"></a> #### `Str::camel()` {#collection-method} The `Str::camel` method converts the given string to `camelCase`: `Str::camel` 函数将给定字符串「蛇式」转化为 `camelCase`「驼峰式」: use Illuminate\Support\Str; $converted = Str::camel('foo_bar'); // fooBar <a name="method-class-basename"></a> #### `class_basename()` {#collection-method} `class_basename` 函数返回被删除了命名空间的指定类的类名: $class = class_basename('Foo\Bar\Baz'); // Baz <a name="method-e"></a> #### `e()` {#collection-method} `e` 函数将默认值为 `true`的 `double_encode` 选项值改为`false` 来运行 `PHP` 的 `htmlspecialchars`函数 : echo e('<html>foo</html>'); // <html>foo</html> <a name="method-ends-with"></a> #### `Str::endsWith()` {#collection-method} `Str::endsWith` 函数判断指定的字符串是否以给定的值结尾: $result = Str::endsWith('This is my name', 'name'); // true <a name="method-kebab-case"></a> #### `Str::kebab()` {#collection-method} `Str::kebab` 函数将给定的「驼峰式」字符串转化为 `kebab-case`「短横式」字符串: use Illuminate\Support\Str; $converted = Str::kebab('fooBar'); // foo-bar <a name="method-preg-replace-array"></a> #### `preg_replace_array()` {#collection-method} `preg_replace_array` 函数使用数组顺序替换字符串中的给定模式: $string = 'The event will take place between :start and :end'; $replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string); // 活动将在 8:30 至 9:00 之间进行 <a name="method-snake-case"></a> #### `Str::snake()` {#collection-method} `Str::snake` 函数将给定的字符串转换为 `snake_case`「蛇式」: use Illuminate\Support\Str; $converted = Str::snake('fooBar'); // foo_bar <a name="method-starts-with"></a> #### `Str::startsWith()` {#collection-method} `Str::startsWith` 函数判断给定的字符串的开头是否是指定值: use Illuminate\Support\Str; $result = Str::startsWith('This is my name', 'This'); // true <a name="method-str-after"></a> #### `Str::after()` {#collection-method} `Str::after` 函数返回在字符串中指定值之后的所有内容: use Illuminate\Support\Str; $slice = Str::after('This is my name', 'This is'); // ' my name' <a name="method-str-before"></a> #### `Str::before()` {#collection-method} `Str::before` 函数返回在字符串中指定值之前的所有内容: use Illuminate\Support\Str; $slice = Str::before('This is my name', 'my name'); // 'This is ' <a name="method-str-contains"></a> #### `Str::contains()` {#collection-method} `Str::contains` 函数判断给定的字符串是否包含给定的值(区分大小写): use Illuminate\Support\Str; $contains = Str::contains('This is my name', 'my'); // true 你也可以传递一个数组形式的值来判断字符串中是否包含任何值: use Illuminate\Support\Str; $contains = Str::contains('This is my name', ['my', 'foo']); // true <a name="method-str-finish"></a> #### `Str::finish()` {#collection-method} `Str::finish` 函数将给定的字符串以给定的值结尾返回(如果它尚未以给定值结尾): use Illuminate\Support\Str; $adjusted = Str::finish('this/string', '/'); // this/string/ $adjusted = Str::finish('this/string/', '/'); // this/string/ <a name="method-str-is"></a> #### `Str::is()` {#collection-method} `Str::is` 函数判断给定的字符串是否匹配给定的模式。星号 * 可以用来表示通配符: use Illuminate\Support\Str; $matches = Str::is('foo*', 'foobar'); // true $matches = Str::is('baz*', 'foobar'); // false <a name="method-str-limit"></a> #### `Str::limit()` {#collection-method} `Str::limit` 函数按给定的长度截断给定的字符串: use Illuminate\Support\Str; $truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20); // The quick brown fox... 你也可以传递第三个参数来改变将被追加到最后的字符串: use Illuminate\Support\Str; $truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); // The quick brown fox (...) <a name="method-str-ordered-uuid"></a> #### `Str::orderedUuid()` {#collection-method} The `Str::orderedUuid` 方法高效生成一个可存储在索引数据库列中的「第一时间」 UUID: use Illuminate\Support\Str; return (string) Str::orderedUuid(); <a name="method-str-plural"></a> #### `Str::plural()` {#collection-method} `Str::plural` 函数将字符串转换为复数形式。该函数目前仅支持英文: use Illuminate\Support\Str; $plural = Str::plural('car'); // cars $plural = Str::plural('child'); // children 你可以提供一个整数作为函数的第二个参数来检索字符串的单数或复数形式: use Illuminate\Support\Str; $plural = Str::plural('child', 2); // children $plural = Str::plural('child', 1); // child <a name="method-str-random"></a> #### `Str::random()` {#collection-method} `Str::random` 函数生成一个指定长度的随机字符串。这个函数用 PHP 的 `random_bytes` 函数: use Illuminate\Support\Str; $random = Str::random(40); <a name="method-str-replace-array"></a> #### `Str::replaceArray()` {#collection-method} `Str::replaceArray` 函数使用数组顺序替换字符串中的给定值: use Illuminate\Support\Str; $string = 'The event will take place between ? and ?'; $replaced = Str::replaceArray('?', ['8:30', '9:00'], $string); // The event will take place between 8:30 and 9:00 <a name="method-str-replace-first"></a> #### `Str::replaceFirst()` {#collection-method} `Str::replaceFirst` 函数替换字符串中给定值的第一个匹配项: use Illuminate\Support\Str; $replaced = Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog'); // a quick brown fox jumps over the lazy dog <a name="method-str-replace-last"></a> #### `Str::replaceLast()` {#collection-method} `Str::replaceLast` 函数替换字符串中最后一次出现的给定值: use Illuminate\Support\Str; $replaced = Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog'); // the quick brown fox jumps over a lazy dog <a name="method-str-singular"></a> #### `Str::singular()` {#collection-method} `Str::singular` 函数将字符串转换为单数形式。该函数目前仅支持英文: use Illuminate\Support\Str; $singular = Str::singular('cars'); // car $singular = Str::singular('children'); // child <a name="method-str-slug"></a> #### `Str::slug()` {#collection-method} `Str::slug` 函数将给定的字符串生成一个 URL 友好的 「slug」 : use Illuminate\Support\Str; $slug = Str::slug('Laravel 5 Framework', '-'); // laravel-5-framework <a name="method-str-start"></a> #### `Str::start()` {#collection-method} `Str::start` 函数将给定值添加到给定字符串的开始位置(如果字符串尚未以给定值开始): use Illuminate\Support\Str; $adjusted = Str::start('this/string', '/'); // /this/string $adjusted = Str::start('/this/string', '/'); // /this/string <a name="method-studly-case"></a> #### `Str::studly()` {#collection-method} `Str::studly` 函数将给定的字符串转换为 「变种驼峰命名」: use Illuminate\Support\Str; $converted = Str::studly('foo_bar'); // FooBar <a name="method-title-case"></a> #### `Str::title()` {#collection-method} `Str::title` 函数将给定的字符串转换为「首字母大写」: use Illuminate\Support\Str; $converted = Str::title('a nice title uses the correct case'); // A Nice Title Uses The Correct Case <a name="method-trans"></a> #### `trans()` {#collection-method} `trans` 函数使用你的 [本地文件](/docs/{{version}}/localization) 转换给定的翻译密钥: echo trans('messages.welcome'); 如果指定的翻译键不存在,则 `trans` 方法会简单地返回给定的键。所以,就上面的例子而言,如果翻译键不存在, `trans` 方法会返回 `messages.welcome` 。 <a name="method-trans-choice"></a> #### `trans_choice()` {#collection-method} `trans_choice` 函数根据词形变化来翻译给定的翻译键: echo trans_choice('messages.notifications', $unreadCount); 如果指定的翻译键不存在, `trans_choice` 方法会简单地返回给定的键。所以,按照上面的例子,如果翻译键不存在, `trans_choice` 方法会返回 `messages.notifications` 。 <a name="method-str-uuid"></a> #### `Str::uuid()` {#collection-method} `Str::uuid` 方法生成一个 UUID(版本 4): use Illuminate\Support\Str; return (string) Str::uuid(); <a name="urls"></a> ## URLs <a name="method-action"></a> #### `action()` {#collection-method} `action` 函数为指定的控制器动作生成一个 URL 。你不需要传递完整的控制器命名空间。只需要传递相对于 `App\Http\Controllers` 命名空间控制器类名称: $url = action('HomeController@index'); $url = action([HomeController::class, 'index']); 如果该方法接受路由参数,则可以将它们作为方法的第二个参数传递: $url = action('UserController@profile', ['id' => 1]); <a name="method-asset"></a> #### `asset()` {#collection-method} `asset` 函数使用当前请求的协议( HTTP 或 HTTPS )为资源文件生成 URL : $url = asset('img/photo.jpg'); 您可以通过 `ASSET_URL` 在 `.env` 文件中设置变量来配置资产URL主机。如果您在 Amazon S3 等外部服务上托管资产,这将非常有用: // ASSET_URL=http://example.com/assets $url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg <a name="method-secure-asset"></a> #### `secure_asset()` {#collection-method} `secure_asset` 函数使用 HTTPS 协议为资源文件生成 URL: $url = secure_asset('img/photo.jpg'); <a name="method-route"></a> #### `route()` {#collection-method} `route` 函数为给定的命名路由生成一个 URL : $url = route('routeName'); 如果路由接受参数,则可以将它们作为方法的第二个参数传递: $url = route('routeName', ['id' => 1]); 默认情况下, `route` 函数生成的是绝对 URL 。如果你想生成一个相对 URL ,你可以传递 `false` 作为第三个参数: $url = route('routeName', ['id' => 1], false); <a name="method-secure-url"></a> #### `secure_url()` {#collection-method} `secure_url` 函数为给定的路径生成一个标准的 HTTPS URL : $url = secure_url('user/profile'); $url = secure_url('user/profile', [1]); <a name="method-url"></a> #### `url()` {#collection-method} `url` 函数生成给定路径的标准 URL : $url = url('user/profile'); $url = url('user/profile', [1]); 如果没有提供路径,则返回 `Illuminate\Routing\UrlGenerator` 实例: $current = url()->current(); $full = url()->full(); $previous = url()->previous(); <a name="miscellaneous"></a> ## 其他 <a name="method-abort"></a> #### `abort()` {#collection-method} `abort` 函数抛出 [异常处理](/docs/{{version}}/errors#the-exception-handler) 程序呈现的 [ HTTP 异常 ](/docs/{{version}}/errors#http-exceptions) : abort(403); 你也可以提供额外的响应文本和自定义响应标头: abort(403, 'Unauthorized.', $headers); <a name="method-abort-if"></a> #### `abort_if()` {#collection-method} 如果给定的布尔表达式计算结果为 `true`, `abort_if` 函数将抛出一个 HTTP 异常: abort_if(! Auth::user()->isAdmin(), 403); 和 `abort` 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数据作为第四个参数。 <a name="method-abort-unless"></a> #### `abort_unless()` {#collection-method} 如果给定的布尔表达式计算结果为 `false`, `abort_unless` 函数将抛出一个 HTTP 异常: abort_unless(Auth::user()->isAdmin(), 403); 和 `abort` 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数组作为第四个参数。 <a name="method-app"></a> #### `app()` {#collection-method} `app` 函数返回 [服务容器](/docs/{{version}}/container) 实例: $container = app(); 你可以传递一个类或接口名称来从容器中解析它: $api = app('HelpSpot\API'); <a name="method-auth"></a> #### `auth()` {#collection-method} `auth` 函数返回一个 [认证](/docs/{{version}}/authentication) 实例。为了方便起见,你可以使用它来替代 `Auth` Facade : $user = auth()->user(); 如果需要,你可以指定你想要访问的认证实例: $user = auth('admin')->user(); <a name="method-back"></a> #### `back()` {#collection-method} `back` 函数生成一个 [重定向 HTTP 响应](/docs/{{version}}/responses#redirects) 到用户之前的位置: return back($status = 302, $headers = [], $fallback = false); return back(); <a name="method-bcrypt"></a> #### `bcrypt()` {#collection-method} `bcrypt` [哈希](/docs/{{version}}/hashing) 使用 Bcrypt 对给定的值进行散列。你可以使用它替代 `Hash` Facade : $password = bcrypt('my-secret-password'); <a name="method-broadcast"></a> #### `broadcast()` {#collection-method} `broadcast` 函数将 [广播](/docs/{{version}}/broadcasting) 给定的 [事件](/docs/{{version}}/events) 到它的监听器: broadcast(new UserRegistered($user)); <a name="method-blank"></a> #### `blank()` {#collection-method} `blank` 函数判断给定的值是否为空: blank(''); blank(' '); blank(null); blank(collect()); // true blank(0); blank(true); blank(false); // false 如果想使用与 `blank` 函数相反的方法,请看 [`filled`](#method-filled) 方法。 <a name="method-cache"></a> #### `cache()` {#collection-method} `cache` 函数可以从 [缓存](/docs/{{version}}/cache) 中获取值.如果缓存中给定的键不存在,将返回一个可选的默认值: $value = cache('key'); $value = cache('key', 'default'); 你可以通过向函数添加键值对数组来设置缓存项。与此同时,你还应该传递有效的分钟数或者缓存的持续时间来设置缓存过期时间 : cache(['key' => 'value'], 5); cache(['key' => 'value'], now()->addSeconds(10)); <a name="method-class-uses-recursive"></a> #### `class_uses_recursive()` {#collection-method} `class_uses_recursive` 函数返回一个类使用的所有 traits ,包括它所有父类使用的 traits: $traits = class_uses_recursive(App\User::class); <a name="method-collect"></a> #### `collect()` {#collection-method} `collect` 函数根据给定的值创建一个 [collection](/docs/{{version}}/collections) 实例。 $collection = collect(['taylor', 'abigail']); <a name="method-config"></a> #### `config()` {#collection-method} `config` 函数获取 [configuration](/docs/{{version}}/configuration) 变量的值。可以使用「点」语法访问配置的值,其中包括文件的名称和访问的选项,如果访问的配置选项不存在,你可以指定一个默认值并且返回这个默认值: $value = config('app.timezone'); $value = config('app.timezone', $default); 你也可以在运行时通过传递一个键/值对数组来设置配置变量: config(['app.debug' => true]); <a name="method-cookie"></a> #### `cookie()` {#collection-method} `cookie` 函数创建一个新的 [cookie](/docs/{{version}}/requests#cookies) 实例: $cookie = cookie('name', 'value', $minutes); <a name="method-csrf-field"></a> #### `csrf_field()` {#collection-method} `csrf_field` 函数生成一个包含 CSRF 令牌值的 HTML 输入表单字段 `hidden` 。例如,使用 [Blade 语法](/docs/{{version}}/blade): {{ csrf_field() }} <a name="method-csrf-token"></a> #### `csrf_token()` {#collection-method} `csrf_token` 函数获取当前CSRF令牌的值: $token = csrf_token(); <a name="method-dd"></a> #### `dd()` {#collection-method} `dd` 函数打印输出给定的变量并且结束脚本运行: dd($value); dd($value1, $value2, $value3, ...); 如果你不停止执行脚本,那么可以使用 [`dump`](#method-dump) 函数。 <a name="method-decrypt"></a> #### `decrypt()` {#collection-method} `decrypt` 函数可以使用 Laravel 的 [加密解密机制](/docs/{{version}}/encryption): $decrypted = decrypt($encrypted_value); <a name="method-dispatch"></a> #### `dispatch()` {#collection-method} `dispatch` 函数将给定的 [任务](/docs/{{version}}/queues#creating-jobs) 推送到 Laravel [任务队列](/docs/{{version}}/queues)中: dispatch(new App\Jobs\SendEmails); <a name="method-dispatch-now"></a> #### `dispatch_now()` {#collection-method} `dispatch_now` 函数立即运行给定的 [任务](/docs/{{version}}/queues#creating-jobs) 并从 `handle` 方法返回值: $result = dispatch_now(new App\Jobs\SendEmails); <a name="method-dump"></a> #### `dump()` {#collection-method} `dump` 打印给定的变量: dump($value); dump($value1, $value2, $value3, ...); 如果你想要在打印后停止执行脚本,可以使用 [`dd`](#method-dd) 函数。 > {提示}你可以使用 Artisan 中的 `dump-server` 命令拦截所有的 `dump` 调用并把它们显示在控制台窗口而不是浏览器中。 <a name="method-encrypt"></a> #### `encrypt()` {#collection-method} `encrypt` 函数使用 Laravel 的[加解密机制](/docs/{{version}}/encryption) 对给定的值进行加密: $encrypted = encrypt($unencrypted_value); <a name="method-env"></a> #### `env()` {#collection-method} `env` 函数可以获取[环境变量](/docs/{{version}}/configuration#environment-configuration) 配置的值或者返回默认值: $env = env('APP_ENV'); // 返回 'production' 如果 APP_ENV 未设置的话... $env = env('APP_ENV', 'production'); > {注意} 如果你在部署过程中执行了 `config:cache` 命令 ,那么你应该确保只从配置文件中调用 `env` 函数.一旦配置被缓存,`.env` 文件将不再次加载,所有对 `env` 函数的调用将返回 `null`。 <a name="method-event"></a> #### `event()` {#collection-method} `event` 函数向监听器派发给定 [事件](/docs/{{version}}/events) : event(new UserRegistered($user)); <a name="method-factory"></a> #### `factory()` {#collection-method} `factory` 函数根据给定的类、名称和数量创建模型工厂构造器。它能够被用于 [测试](/docs/{{version}}/database-testing#writing-factories) 或 [数据填充](/docs/{{version}}/seeding#using-model-factories): $user = factory(App\User::class)->make(); <a name="method-filled"></a> #### `filled()` {#collection-method} `filled` 函数返回是否不为「空」: filled(0); filled(true); filled(false); // true filled(''); filled(' '); filled(null); filled(collect()); // false [`blank`](#method-blank) 方法与 `filled` 作用相反。 <a name="method-info"></a> #### `info()` {#collection-method} `info` 函数将信息写入 [log](/docs/{{version}}/logging): info('Some helpful information!'); 可以将上下文数据数组传递给此函数: info('User login attempt failed.', ['id' => $user->id]); <a name="method-logger"></a> #### `logger()` {#collection-method} `logger` 函数可以被用于将 `debug` 级别的消息写入 [log](/docs/{{version}}/logging): logger('Debug message'); 可以将上下文数据数组传递给此函数: logger('User has logged in.', ['id' => $user->id]); 如果不带参数调用此函数,它将返回 [logger](/docs/{{version}}/errors#logging) 实例: logger()->error('You are not allowed here.'); <a name="method-method-field"></a> #### `method_field()` {#collection-method} `method_field` 行数生成包含模仿表单 HTTP 动作的 HTML `hidden` 域。下面的例子使用了 [Blade 语法](/docs/{{version}}/blade): <form method="POST"> {{ method_field('DELETE') }} </form> <a name="method-now"></a> #### `now()` {#collection-method} `now` 函数根据当前时间创建一个新的 `Illuminate\Support\Carbon` 实例: $now = now(); <a name="method-old"></a> #### `old()` {#collection-method} `old` 函数 [获取](/docs/{{version}}/requests#retrieving-input) 刷入 session 的 [旧的输入值](/docs/{{version}}/requests#old-input) : $value = old('value'); $value = old('value', 'default'); <a name="method-optional"></a> #### `optional()` {#collection-method} `optional` 函数接受任何参数,并允许你访问该对象上的属性或调用其方法。如果给定对象为 `null`,属性或方法将返回 `null` 而不是引发错误: return optional($user->address)->street; {!! old('name', optional($user)->name) !!} `optional` 函数也接受闭包作为其第二个参数。如果第一个参数提供的值不是 null,闭包将被调用: return optional(User::find($id), function ($user) { return new DummyUser; }); <a name="method-policy"></a> #### `policy()` {#collection-method} `policy` 方法为给定的类获取 [policy](/docs/{{version}}/authorization#creating-policies) 实例: $policy = policy(App\User::class); <a name="method-redirect"></a> #### `redirect()` {#collection-method} `redirect` 函数返回 [重定向 HTTP 响应](/docs/{{version}}/responses#redirects),如果不带参数调用则返回重定向器实例: return redirect($to = null, $status = 302, $headers = [], $secure = null); return redirect('/home'); return redirect()->route('route.name'); <a name="method-report"></a> #### `report()` {#collection-method} `report` 函数使用 [异常处理器](/docs/{{version}}/errors#the-exception-handler) 的 `report` 方法报告异常: report($e); <a name="method-request"></a> #### `request()` {#collection-method} `request` 函数返回当前 [请求](/docs/{{version}}/requests) 实例,或者获取一个输入项: $request = request(); $value = request('key', $default); <a name="method-rescue"></a> #### `rescue()` {#collection-method} `rescue` 函数执行给定的闭包,并且捕获其执行过程中引发的任何异常。捕获的所有异常都将传递给 [异常处理器](/docs/{{version}}/errors#the-exception-handler) 的 `report` 方法;然后继续处理此次请求: return rescue(function () { return $this->method(); }); 还可以为其传递第二个参数。这个参数将作为执行闭包引发异常时的 「默认」值: return rescue(function () { return $this->method(); }, false); return rescue(function () { return $this->method(); }, function () { return $this->failure(); }); <a name="method-resolve"></a> #### `resolve()` {#collection-method} `resolve` 函数使用 [服务容器](/docs/{{version}}/container) 解析给定名称的类或接口的实例: $api = resolve('HelpSpot\API'); <a name="method-response"></a> #### `response()` {#collection-method} `response` 函数创建 [响应](/docs/{{version}}/responses) 实例,或者获得响应工厂的实例: return response('Hello World', 200, $headers); return response()->json(['foo' => 'bar'], 200, $headers); <a name="method-retry"></a> #### `retry()` {#collection-method} `retry` 函数尝试执行给定的回调,直到达到给定的最大尝试阈值。如果回调没有抛出异常,回调返回值将被返回。如果回调抛出异常,将自动重试。达到最大尝试次数,将抛出异常: return retry(5, function () { // Attempt 5 times while resting 100ms in between attempts... }, 100); <a name="method-session"></a> #### `session()` {#collection-method} `session` 函数用于获取或设置 [session](/docs/{{version}}/session) 值: $value = session('key'); 可以向该函数传递键值对数组来设置 session 值: session(['chairs' => 7, 'instruments' => 3]); 不带参数调用此函数,则返回存储在 session 中的值: $value = session()->get('key'); session()->put('key', $value); <a name="method-tap"></a> #### `tap()` {#collection-method} `tap` 函数接受两个参数: 任意 `$value` 和闭包。 `$value` 将被传递给闭包,并被 `tap` 函数返回。与闭包的返回值无关: $user = tap(User::first(), function ($user) { $user->name = 'taylor'; $user->save(); }); 如果没有向 `tap` 函数传递闭包,可以调用给定 `$value` 的任意方法。调用此方法的返回值永远是 `$value`,无论方法在其定义中返回什么。例如,Eloquent `update` 方法指定返回一个整数。但是,我们可以通过 `tap` 函数链式调用 `update` 方法强制其返回模型自身: $user = tap($user)->update([ 'name' => $name, 'email' => $email, ]); <a name="method-today"></a> #### `today()` {#collection-method} `today` 函数根据当前日期创建新的 `Illuminate\Support\Carbon` 实例: $today = today(); <a name="method-throw-if"></a> #### `throw_if()` {#collection-method} 在给定的布尔表达式结果为 `true` 时,`throw_if` 函数抛出给定的异常: throw_if(! Auth::user()->isAdmin(), AuthorizationException::class); throw_if( ! Auth::user()->isAdmin(), AuthorizationException::class, 'You are not allowed to access this page' ); <a name="method-throw-unless"></a> #### `throw_unless()` {#collection-method} 在给定的布尔表达式结果为 `false` 时,`throw_unless` 函数抛出给定的异常: throw_unless(Auth::user()->isAdmin(), AuthorizationException::class); throw_unless( Auth::user()->isAdmin(), AuthorizationException::class, 'You are not allowed to access this page' ); <a name="method-trait-uses-recursive"></a> #### `trait_uses_recursive()` {#collection-method} `trait_uses_recursive` 返回被 trait 使用的全部 trait: $traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class); <a name="method-transform"></a> #### `transform()` {#collection-method} `transform` 函数执行基于(非 [空](#method-blank) )给定值的 `闭包`,并返回 `闭包` 的结果: $callback = function ($value) { return $value * 2; }; $result = transform(5, $callback); // 10 还可以传递一个默认值或 `闭包` 作为该函数的第三个参数。如果给定的值为空时,返回该值: $result = transform(null, $callback, 'The value is blank'); // The value is blank <a name="method-validator"></a> #### `validator()` {#collection-method} `validator` 函数根据指定的参数创建一个新的 [验证器](/docs/{{version}}/validation) 实例。方便起见可以用它来代替 `Validator` facade: $validator = validator($data, $rules, $messages); <a name="method-value"></a> #### `value()` {#collection-method} `value` 函数返回给定值。如果传递 `闭包` 给此函数,将执行 `闭包` 并返回闭包调用的结果: $result = value(true); // true $result = value(function () { return false; }); // false <a name="method-view"></a> #### `view()` {#collection-method} `view` 函数获取一个 [view](/docs/{{version}}/views) 实例: return view('auth.login'); <a name="method-with"></a> #### `with()` {#collection-method} `with` 函数返回给定的值。如果传递了一个 `Closure` 给第二个参数,那么会返回 `Closure` 执行的结果: $callback = function ($value) { return (is_numeric($value)) ? $value * 2 : 0; }; $result = with(5, $callback); // 10 $result = with(null, $callback); // 0 $result = with(5, null); // 5