辅助函数

未匹配的标注
本文档最新版为 10.x,旧版本可能放弃维护,推荐阅读最新版!

辅助函数

简介

Laravel 包含各种各样的「全局」PHP辅助函数,框架本身也大量的使用了这些功能函数;如果你觉的方便,你可以在你的应用中任意使用这些函数.

可用方法

数组 & 对象

路径

字符串

URLs

其他

方法列表

数组 & 对象

array_add()

如果给定的键不存在数组中,那么array_add函数将会把给定的键/值对添加到数组中:

$array = array_add(['name' => 'Desk'], 'price', 100);

// ['name' => 'Desk', 'price' => 100]

array_collapse()

array_collapse函数将多个数组合并为一个数组;

$array = array_collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

// [1, 2, 3, 4, 5, 6, 7, 8, 9] 

array_divide()

array_divide 函数返回一个二维数组,一个值包含原始数组的键,另一个值包含原始数组的值.

[$keys, $values] = array_divide(['name' => 'Desk']);

// $keys: ['name']  多维数组中的第0个值

// $values: ['Desk'] 多维数组中的第1个值

array_dot()

array_dot函数将多维数组中所有的键平铺到一维数组中,新数组使用「.」符号表示层级包含关系:

$array = ['products' => ['desk' => ['price' => 100]]];

$flattened = array_dot($array);

// ['products.desk.price' => 100]

array_except()

array_except函数从数组中删除给定的键/值对:

$array = ['name' => 'Desk', 'price' => 100];

$filtered = array_except($array, ['price']);

// ['name' => 'Desk']

array_first()

array_first函数返回数组中通过指定测试的第一个元素:

$array = [100, 200, 300];

$first = array_first($array, function ($value, $key) {
    return $value >= 150;
});

// 200

将默认值作为第三个参数传递给该方法, 如果数组中没有值通过测试,则返回默认值.

$first = array_first($array, $callback, $default);

array_flatten()

array_flatten 函数将多维数组中数组的值取出平铺为一维数组:

$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];

$flattened = array_flatten($array);

// ['Joe', 'PHP', 'Ruby']

array_forget()

array_forget函数使用「点」符号从深度嵌套的数组中删除给定的键/值对:

$array = ['products' => ['desk' => ['price' => 100]]];

array_forget($array, 'products.desk');

// ['products' => []]

array_get()

array_get 函数使用「点」符号从深度嵌套的数组中根据指定键检索值:

$array = ['products' => ['desk' => ['price' => 100]]];

$price = array_get($array, 'products.desk.price');

// 100

array_get 函数也接受一个默认值,如果没有找到特定的键,将返回默认值:

$discount = array_get($array, 'products.desk.discount', 0);

// 0

array_has()

array_has 函数使用「点」符号查找数组中是否存在指定的一个或多个键:

$array = ['product' => ['name' => 'Desk', 'price' => 100]];

$contains = array_has($array, 'product.name');

// true 

$contains = array_has($array, ['product.price', 'product.discount']);

// false 

array_last()

array_last 函数返回数组中通过指定测试的最后一个元素:

$array = [100, 200, 300, 110];

$last = array_last($array, function ($value, $key) {
    return $value >= 150;
});

// 300

将默认值作为第三个参数传递给该方法,如果没有值通过指定测试,则返回该默认值:

$last = array_last($array, $callback, $default);

array_only()

array_only 函数只从指定数组中返回指定的键/值对:

$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];

$slice = array_only($array, ['name', 'price']);

// ['name' => 'Desk', 'price' => 100]

array_pluck()

array_pluck 函数从数组中检索给定键的所有值:

$array = [
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
];

$names = array_pluck($array, 'developer.name');

// ['Taylor', 'Abigail']

你也可以指定获取的结果的键:

$names = array_pluck($array, 'developer.name', 'developer.id');

// [1 => 'Taylor', 2 => 'Abigail']

array_prepend()

array_prepend函数将一个值插入到数组的开始位置:

$array = ['one', 'two', 'three', 'four'];

$array = array_prepend($array, 'zero');

// ['zero', 'one', 'two', 'three', 'four']

如果你需要,你可以指定你插入值的键:

$array = ['price' => 100];

$array = array_prepend($array, 'Desk', 'name');

// ['name' => 'Desk', 'price' => 100]

array_pull()

array_pull 函数从数组中返回指定键的值并删除此键/值对:

$array = ['name' => 'Desk', 'price' => 100];

$name = array_pull($array, 'name');

// $name: Desk

// $array: ['price' => 100]

默认值可以作为第三个参数传递给该方法,如果键不存在,则返回该值:

$value = array_pull($array, $key, $default);

array_random()

array_random 函数从数组中随机返回一个值:

$array = [1, 2, 3, 4, 5];

$random = array_random($array);

// 4 - (retrieved randomly)

你也可以将返回值的数量作为可选的第二个参数传递给该方法,请注意,提供这个参数会返回一个数组,即便是你只需要一项:

$items = array_random($array, 2);

// [2, 5] - (retrieved randomly)

array_set()

array_set 函数使用「.」符号在多维数组中设置指定键的值:

$array = ['products' => ['desk' => ['price' => 100]]];

array_set($array, 'products.desk.price', 200);

// ['products' => ['desk' => ['price' => 200]]]

array_sort()

array_sort函数根据数组的值对数组进行排序:

$array = ['Desk', 'Table', 'Chair'];

$sorted = array_sort($array);

// ['Chair', 'Desk', 'Table']

你也可以根据给定闭包返回的结果对数组进行排序:

$array = [
    ['name' => 'Desk'],
    ['name' => 'Table'],
    ['name' => 'Chair'],
];

$sorted = array_values(array_sort($array, function ($value) {
    return $value['name'];
}));

/*
    [
        ['name' => 'Chair'],
        ['name' => 'Desk'],
        ['name' => 'Table'],
    ]
*/

array_sort_recursive()

array_sort_recursive 函数使用 sort函数对数组进行递归排序:

$array = [
    ['Roman', 'Taylor', 'Li'],
    ['PHP', 'Ruby', 'JavaScript'],
];

$sorted = array_sort_recursive($array);

/*
    [
        ['Li', 'Roman', 'Taylor'],
        ['JavaScript', 'PHP', 'Ruby'],
    ]
*/

array_where()

array_where函数使用给定闭包返回的结果过滤数组:

$array = [100, '200', 300, '400', 500];

$filtered = array_where($array, function ($value, $key) {
    return is_string($value);
});

// [1 => '200', 3 => '400']

array_wrap()

array_wrap函数将给定的值变为一个数组, 如果给定的值已经是数组,则不改变:

$string = 'Laravel';

$array = array_wrap($string);

// ['Laravel']

如果给定的值是空,则返回一个空数组:

$nothing = null;

$array = array_wrap($nothing);

// []

data_fill()

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],
        ],
    ]
*/

data_get()

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_set()

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]]]

head()

head 函数返回给定数组中的第一个元素:

$array = [100, 200, 300];

$first = head($array);

// 100

last()

last 函数返回给定数组中的最后一个元素:

$array = [100, 200, 300];

$last = last($array);

// 300

路径

app_path()

app_path函数返回app目录的完整路径.你也可以使用 app_path函数来设置应用程序app目录的完整路径:

$path = app_path();

$path = app_path('Http/Controllers/Controller.php');

base_path()

base_path函数返回项目根目录的完整路径.你也可以使用base_path函数设置项目根目录的完整路径:

$path = base_path();

$path = base_path('vendor/bin');

config_path()

config_path函数返回config 目录的完整路径.你也可以使用config_path函数设置应用程序config 目录中给定文件的完整路径:

$path = config_path();

$path = config_path('app.php');

database_path()

database_path 函数返回database目录的完整路径.你也可以使用 database_path函数来设置database目录中给定文件的完整路径:

$path = database_path();

$path = database_path('factories/UserFactory.php');

mix()

mix函数返回 版本化 Mix 文件 的路径:

$path = mix('css/app.css');

public_path()

public_path函数返回public目录的完整路径.你也可以使用 public_path函数来生成public目录中给定文件的完整路径:

$path = public_path();

$path = public_path('css/app.css');

resource_path()

resource_path 函数返回resources目录的完整路径.你也可以使用 resource_path 函数来生成资源文件中给定文件的完整路径:

$path = resource_path();

$path = resource_path('assets/sass/app.scss');

storage_path()

storage_path 函数返回 storage目录的完整路径.你也可以使用 storage_path函数来设置存储目录下指定文件的完整路径 :

$path = storage_path();

$path = storage_path('app/file.txt');

字符串

__()

__ 函数使用你的本地化文件来翻译给定的翻译字符串或翻译键:

echo __('Welcome to our application');

echo __('messages.welcome');

如果指定的翻译字符串或翻译键不存在,__ 函数将返回给定的值.所以,按照上面的例子,如果翻译键 messages.welcome不存在,__ 函数会将其直接返回.

camel_case()

camel_case 函数将给定字符串「短横式」转化为 camelCase「驼峰式」:

$converted = camel_case('foo_bar');

// fooBar

class_basename()

class_basename函数返回被删除了命名空间的指定类的类名:

$class = class_basename('Foo\Bar\Baz');

// Baz

e()

e 函数将默认值为truedouble_encode 选项值改为false来运行 PHPhtmlspecialchars函数 :

echo e('<html>foo</html>');

// <html>foo</html>

ends_with()

ends_with函数判断指定的字符串是否以给定的值结尾:

$result = ends_with('This is my name', 'name');

// true

kebab_case()

kebab_case函数将给定的「驼峰式」字符串转化为「短横式」字符串:

$converted = kebab_case('fooBar');

// foo-bar

preg_replace_array()

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 之间进行

snake_case()

snake_case 函数将给定的字符串转换为 「蛇式」:

$converted = snake_case('fooBar');

// foo_bar

starts_with()

starts_with 函数判断给定的字符串的开头是否是指定值:

$result = starts_with('This is my name', 'This');

// true

str_after()

str_after 函数返回在字符串中指定值之后的所有内容:

$slice = str_after('This is my name', 'This is');

// ' my name'

str_before()

str_before 函数返回在字符串中指定值之前的所有内容:

$slice = str_before('This is my name', 'my name');

// 'This is '

str_contains()

str_contains 函数判断给定的字符串是否包含给定的值(区分大小写):

$contains = str_contains('This is my name', 'my');

// true

你也可以传递一个数组形式的值来判断字符串中是否包含任何值:

$contains = str_contains('This is my name', ['my', 'foo']);

// true

str_finish()

str_finish 函数将给定的字符串以给定的值结尾返回(如果它尚未以给定值结尾):

$adjusted = str_finish('this/string', '/');

// this/string/

$adjusted = str_finish('this/string/', '/');

// this/string/

str_is()

str_is 函数判断给定的字符串是否匹配给定的模式。星号 * 可以用来表示通配符:

$matches = str_is('foo*', 'foobar');

// true

$matches = str_is('baz*', 'foobar');

// false

str_limit()

str_limit 函数按给定的长度截断给定的字符串:

$truncated = str_limit('The quick brown fox jumps over the lazy dog', 20);

// The quick brown fox...

你也可以传递第三个参数来改变将被追加到最后的字符串:

$truncated = str_limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');

// The quick brown fox (...)

Str::orderedUuid()

Str::orderedUuid 方法高效生成一个可存储在索引数据库列中的「第一时间」UUID:

use Illuminate\Support\Str;

return (string) Str::orderedUuid();

str_plural()

str_plural 函数将字符串转换为复数形式。该函数目前仅支持英文:

$plural = str_plural('car');

// cars

$plural = str_plural('child');

// children

你可以提供一个整数作为函数的第二个参数来检索字符串的单数或复数形式:

$plural = str_plural('child', 2);

// children

$plural = str_plural('child', 1);

// child

str_random()

str_random 函数生成一个指定长度的随机字符串。这个函数用 PHP 的 random_bytes 函数:

$random = str_random(40);

str_replace_array()

str_replace_array 函数使用数组顺序替换字符串中的给定值:

$string = '该活动将于 ? 至 ? 之间举行';

$replaced = str_replace_array('?', ['8:30', '9:00'], $string);

// 该活动将于 8:30 至 9:00 之间举行

str_replace_first()

str_replace_first 函数替换字符串中给定值的第一个匹配项:

$replaced = str_replace_first('the', 'a', 'the quick brown fox jumps over the lazy dog');

// a quick brown fox jumps over the lazy dog

str_replace_last()

str_replace_last 函数替换字符串中最后一次出现的给定值:

$replaced = str_replace_last('the', 'a', 'the quick brown fox jumps over the lazy dog');

// the quick brown fox jumps over a lazy dog

str_singular()

str_singular 函数将字符串转换为单数形式。该函数目前仅支持英文:

$singular = str_singular('cars');

// car

$singular = str_singular('children');

// child

str_slug()

str_slug 函数将给定的字符串生成一个 URL 友好的「slug」:

$slug = str_slug('Laravel 5 Framework', '-');

// laravel-5-framework

str_start()

str_start 函数将给定值添加到给定字符串的开始位置(如果字符串尚未以给定值开始)

$adjusted = str_start('this/string', '/');

// /this/string

$adjusted = str_start('/this/string', '/');

// /this/string

studly_case()

studly_case 函数将给定的字符串转换为 「变种驼峰命名」:

$converted = studly_case('foo_bar');

// FooBar

title_case()

title_case 函数将给定的字符串转换为「首字母大写」:

$converted = title_case('a nice title uses the correct case');

// A Nice Title Uses The Correct Case

trans()

trans 函数使用你的 本地文件 来翻译给定的翻译字符串或翻译健:

echo trans('messages.welcome');

如果指定的翻译健不存在,则 trans 方法会简单地返回给定的健。所以,就上面的例子而言,如果翻译健不存在,trans 方法会返回 messages.welcome

trans_choice()

trans_choice 函数根据词形变化来翻译给定的翻译健:

echo trans_choice('messages.notifications', $unreadCount);

如果指定的翻译健不存在,trans_choice 方法会简单地返回给定的健。所以,按照上面的例子,如果翻译健不存在,trans_choice 方法会返回 messages.notifications

Str::uuid()

Str::uuid 方法生成一个 UUID(版本 4):

use Illuminate\Support\Str;

return (string) Str::uuid();

URLs

action()

action 函数为指定的控制器动作生成一个 URL。你不需要传递完整的控制器命名空间。只需要传递相对于 App\Http\Controllers 命名空间控制器类名称:

$url = action('HomeController@index');

$url = action([HomeController::class, 'index']);

如果该方法接受路由参数,则可以将它们作为方法的第二个参数传递:

$url = action('UserController@profile', ['id' => 1]);

asset()

asset 函数使用当前请求的协议(HTTP 或 HTTPS)为资源文件生成 URL:

$url = asset('img/photo.jpg');

secure_asset()

secure_asset 函数使用 HTTPS 协议为资源文件生成 URL:

$url = secure_asset('img/photo.jpg');

route()

route 函数为给定的命名路由生成一个 URL:

$url = route('routeName');

如果路由接受参数,则可以将它们作为方法的第二个参数传递:

$url = route('routeName', ['id' => 1]);

默认情况下,route 函数生成的是绝对 URL。如果你想生成一个相对 URL,你可以传递 false 作为第三个参数:

$url = route('routeName', ['id' => 1], false);

secure_url()

secure_url 函数为给定的路径生成一个标准的 HTTPS URL:

$url = secure_url('user/profile');

$url = secure_url('user/profile', [1]);

url()

url 函数生成给定路径的标准 URL:

$url = url('user/profile');

$url = url('user/profile', [1]);

如果没有提供路径,则返回 Illuminate\Routing\UrlGenerator 实例:

$current = url()->current();

$full = url()->full();

$previous = url()->previous();

其他

abort()

abort 函数抛出 异常处理 程序呈现的 HTTP 异常

abort(403);

你也可以提供额外的响应文本和自定义响应标头:

abort(403, 'Unauthorized.', $headers);

abort_if()

如果给定的布尔表达式计算结果为 trueabort_if 函数将抛出一个 HTTP 异常:

abort_if(! Auth::user()->isAdmin(), 403);

abort 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数据作为第四个参数。

abort_unless()

如果给定的布尔表达式计算结果为 falseabort_unless 函数将抛出一个 HTTP 异常:

abort_unless(Auth::user()->isAdmin(), 403);

abort 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数组作为第四个参数。

app()

app 函数返回 服务容器 实例:

$container = app();

你可以传递一个类或接口名称来从容器中解析它:

$api = app('HelpSpot\API');

auth()

auth 函数返回一个 认证 实例。为了方便起见,你可以使用它来替代 Auth Facade:

$user = auth()->user();

如果需要,你可以指定你想要访问的认证实例:

$user = auth('admin')->user();

back()

back 函数生成一个 重定向 HTTP 响应 到用户之前的位置:

return back($status = 302, $headers = [], $fallback = false);

return back();

bcrypt()

bcrypt 哈希 使用 Bcrypt 对给定的值进行散列。你可以使用它替代Hash Facade:

$password = bcrypt('my-secret-password');

broadcast()

broadcast 函数将 广播 给定的 事件 到它的监听器:

broadcast(new UserRegistered($user));

blank()

blank函数判断给定的值是否为空:

blank('');
blank('   ');
blank(null);
blank(collect());

// true

blank(0);
blank(true);
blank(false);

// false

如果想使用与blank函数相反的方法,请看filled 方法.

cache()

cache函数可以从缓存中获取值.如果缓存中给定的键不存在,将返回一个可选的默认值:

$value = cache('key', 'default');

你可以通过向函数添加键值对数组来设置缓存项.与此同时,你还应该传递有效的分钟数或者缓存的持续时间来设置缓存过期时间 :

cache(['key' => 'value'], 5);

cache(['key' => 'value'], now()->addSeconds(10));

class_uses_recursive()

class_uses_recursive 函数返回一个类使用的所有 traits ,包括它所有父类使用的 traits:

$traits = class_uses_recursive(App\User::class);

collect()

collect函数根据给定的值创建一个 集合 实例:

$collection = collect(['taylor', 'abigail']);

config()

config 函数获取 配置 变量的值. 可以使用「点」语法访问配置的值, 其中包括文件的名称和访问的选项,如果访问的配置选项不存在,你可以指定一个默认值并且返回这个默认值.

$value = config('app.timezone');

$value = config('app.timezone', $default);

你也可以在运行时通过传递一个键/值对数组来设置配置变量:

config(['app.debug' => true]);

cookie()

cookie 函数创建一个新的 cookie 实例:

$cookie = cookie('name', 'value', $minutes);

csrf_field()

csrf_field 函数生成一个包含CSRF令牌值的HTML 输入表单字段 hidden ,例如,使用 Blade 语法:

{{ csrf_field() }}

csrf_token()

csrf_token 函数获取当前CSRF令牌的值:

$token = csrf_token();

dd()

dd 函数打印输出给定的变量并且结束脚本运行:

dd($value);

dd($value1, $value2, $value3, ...);

如果你不停止执行脚本,那么可以使用 dump 函数.

decrypt()

decrypt 函数可以使用 Laravel的 加解密机制来解密给定的值:

$decrypted = decrypt($encrypted_value);

dispatch()

dispatch 函数将给定的 任务 推送到Laravel 任务队列 中:

dispatch(new App\Jobs\SendEmails);

dispatch_now()

dispatch_now 函数立即运行给定的 任务 ,并从其 handle 方法返回值:

$result = dispatch_now(new App\Jobs\SendEmails);

dump()

dump 函数打印给定的变量:

dump($value);

dump($value1, $value2, $value3, ...);

如果你想要在打印后停止执行脚本,可以使用 dd 函数.

{tip} 你可以使用 Artisan中的 dump-server 命令拦截所有 dump 调用, 并将它们显式在控制台窗口而不是浏览器中.

encrypt()

encrypt 函数使用Laravel的 加解密机制 对给定的值进行加密:

$encrypted = encrypt($unencrypted_value);

env()

env 函数可以获取 环境变量 配置的值或者返回默认值:

$env = env('APP_ENV');

// Returns 'production' if APP_ENV is not set...
$env = env('APP_ENV', 'production');

{note} 如果你在部署过程中执行了 config:cache 命令 ,那么你应该确保只从配置文件中调用 env 函数.一旦配置被添加到缓存中,.env 文件则不会再次被加载,并且所有对 env 函数的调用将返回 null

event()

event 函数将给定的 事件 分派给它的监听器:

event(new UserRegistered($user));

factory()

factory函数根据给定的类,名称,数量创建一个模型工厂构建器,它可以在 测试 或者 数据填充 中使用:

$user = factory(App\User::class)->make();

filled()

filled函数判断给定的值不为「空」:

filled(0);
filled(true);
filled(false);

// true

filled('');
filled('   ');
filled(null);
filled(collect());

// false

要使用与filled函数相反的功能, 请看blank 方法.

info()

info 函数将信息写入 日志:

info('Some helpful information!');

在上下文中有关联的数组也可以传递给数组:

info('User login attempt failed.', ['id' => $user->id]);

logger()

logger 函数可以将一个 debug 级别的消息写入到 日志中:

logger('Debug message');

有前后关系的数组也可以传值给数组:

logger('User has logged in.', ['id' => $user->id]);

如果没有传递任何参数给函数,则会返回 日志 的实例:

logger()->error('You are not allowed here.');

method_field()

method_field 函数生成一个HTML hidden 输入框包含表单的HTTP动作的欺骗值.例如,使用 Blade 语法:

<form method="POST">
    {{ method_field('DELETE') }}
</form>

now()

now 函数为当前时间创建一个新的 Illuminate\Support\Carbon 实例:

$now = now();

old()

old 函数 检索 会话中闪存的 旧输入 值:

$value = old('value');

$value = old('value', 'default');

optional()

optional 函数可以接收任何参数,并且允许你访问该对象的属性或者调用其方法,如果给定的对象是null,属性和方法将返回null,而不会报错:

return optional($user->address)->street;

{!! old('name', optional($user)->name) !!}

optional 函数也可以接收一个闭包作为第二个参数,如果给定的第一个参数不为空,则执行闭包:

return optional(User::find($id), function ($user) {
    return new DummyUser;
});

policy()

policy 方法为指定的类检索这个类的 策略 实例:

$policy = policy(App\User::class);

redirect()

redirect 函数返回一个 重定向 HTTP 响应, 或者如果没有传递参数,则返回重定向实例:

return redirect($to = null, $status = 302, $headers = [], $secure = null);

return redirect('/home');

return redirect()->route('route.name');

report()

report 函数将会使用 异常处理程序 里的 report 方法来报告异常:

report($e);

request()

request函数返回当前获取的 请求 实例或者获取输入项:

$request = request();

$value = request('key', $default);

rescue()

rescue 函数执行给定的闭包并且捕获在执行期间发生的任何异常.所有被捕获的异常将会被发送到 异常处理程序 report 方法; 然而,该请求还会继续执行:

return rescue(function () {
    return $this->method();
});

你也可以向 rescue 函数传递第二个参数,这个参数将作为默认值,如果在执行闭包时发生异常,返回默认值:

return rescue(function () {
    return $this->method();
}, false);

return rescue(function () {
    return $this->method();
}, function () {
    return $this->failure();
});

resolve()

resolve 函数使用 服务容器将给定的类或接口解析为其实例:

$api = resolve('HelpSpot\API');

response()

response 函数可以创建 响应 实例或者获取响应工厂的实例:

return response('Hello World', 200, $headers);

return response()->json(['foo' => 'bar'], 200, $headers);

retry()

retry 函数尝试执行给定的回调,直到达到给定的最大尝试次数.如果回调没有抛出异常,则返回设置的返回值, 如果回调抛出了异常,将会自动重试执行.如果重试超过最大尝试次数,将会抛出异常.

return retry(5, function () {
    // Attempt 5 times while resting 100ms in between attempts...
}, 100);

session()

session 函数可以用来获取或者设置 session 值:

$value = session('key');

你可以通过传一个键/值对数组给函数来设置值:

session(['chairs' => 7, 'instruments' => 3]);

如果没有给函数传值,则会返回 Session 存储:

$value = session()->get('key');

session()->put('key', $value);

tap()

tap 函数接收两个参数:一个任意的 $value 和一个闭包. 这个值将会传递给闭包,并且由 tap 函数返回.不需要在闭包中使用 return 返回值:

$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,
]);

today()

today 函数为当前日期创建一个新的Illuminate\Support\Carbon 实例 :

$today = today();

throw_if()

如果给定的布尔表达式的结果为 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'
);

throw_unless()

如果给定的布尔表达式的结果为 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'
);

trait_uses_recursive()

trait_uses_recursive 函数返回一个类使用的所有trait:

$traits = trait_uses_recursive(\Illuminate\Notifications\Notifiable::class);

transform()

transform 函数如果传递的参数不为空,(可以通过 blank 函数判断) ,则对指定值开始执行 Closure,并且返回 Closure的结果:

$callback = function ($value) {
    return $value * 2;
};

$result = transform(5, $callback);

// 10

默认值或者闭包可以以第三个参数的方式传递给该函数,默认值在给定值为空的情况下返回:

$result = transform(null, $callback, 'The value is blank');

// The value is blank

validator()

validator 函数通过给定的参数创建一个新的 验证器 实例 ,方便起见,你可以用它来替代 Validator 代理 :

$validator = validator($data, $rules, $messages);

value()

value 函数返回给定的值,然而,如果传递了参数 Closure 给函数,将会返回 Closure 执行的结果:

$result = value(true);

// true

$result = value(function () {
    return false;
});

// false

view()

view 函数获取一个 视图 实例:

return view('auth.login');

with()

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

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/laravel/5.7/hel...

译文地址:https://learnku.com/docs/laravel/5.7/hel...

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
贡献者:7
讨论数量: 0
发起讨论 查看所有版本


暂无话题~