辅助函数

简介

Laravel包含许多PHP辅助函数。框架自身使用了许多这些函数;不过,如果觉得方便,也可以自由地在你的应用中使用它们。

现有方法

数组

路径

字串

URL

其他

方法列表

数组

array_add() {#collection-method .first-collection-method}

array_add 函数向数组中添加一个键-值对(如果给定的键不存在):

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

array_collapse() {#collection-method}

The array_collapse function collapse an array of arrays into a single array:

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

array_divide() {#collection-method}

array_divide 返回两个数组,一个包含原数组的所有键,另一个包含原数组的所有值:

  1. list($keys, $values) = array_divide(['name' => 'Desk']);
  2. // $keys: ['name']
  3. // $values: ['Desk']

array_dot() {#collection-method}

array_dot 函数将一个多维数组转换为一维数组,并使用点号指示深度:

  1. $array = array_dot(['foo' => ['bar' => 'baz']]);
  2. // ['foo.bar' => 'baz'];

array_except() {#collection-method}

array_except 方法从一个数组中移除指定的键/值对:

  1. $array = ['name' => 'Desk', 'price' => 100];
  2. $array = array_except($array, ['price']);
  3. // ['name' => 'Desk']

array_first() {#collection-method}

array_first 方法返回数组中第一个通过判断返回为真的元素:

  1. $array = [100, 200, 300];
  2. $value = array_first($array, function ($key, $value) {
  3. return $value >= 150;
  4. });
  5. // 200

默认值可作为第三个参数传入。如果没有值通过判断,将返回默认值:

  1. $value = array_first($array, $callback, $default);

array_flatten() {#collection-method}

array_flatten 方法将一个多维数组转换为一维数组:

  1. $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
  2. $array = array_flatten($array);
  3. // ['Joe', 'PHP', 'Ruby'];

array_forget() {#collection-method}

array_forget 方法基于点号路径从一个深度嵌套的数组中移除指定的键/值对:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. array_forget($array, 'products.desk');
  3. // ['products' => []]

array_get() {#collection-method}

array_get 方法基于点号路径从一个深度嵌套的数组中取出值:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. $value = array_get($array, 'products.desk');
  3. // ['price' => 100]

array_get 方法也接受默认值,如果指定的键未找到,返回默认值:

  1. $value = array_get($array, 'names.john', 'default');

array_has() {#collection-method}

The array_has function checks that a given item exists in an array using “dot” notation:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. $hasDesk = array_has($array, ['products.desk']);
  3. // true

array_only() {#collection-method}

array_only 方法从给定的数组中返回指定的键/值对:

  1. $array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
  2. $array = array_only($array, ['name', 'price']);
  3. // ['name' => 'Desk', 'price' => 100]

array_pluck() {#collection-method}

array_pluck 方法从给定的数组中提取出键/值对:

  1. $array = [
  2. ['developer' => ['id' => 1, 'name' => 'Taylor']],
  3. ['developer' => ['id' => 2, 'name' => 'Abigail']],
  4. ];
  5. $array = array_pluck($array, 'developer.name');
  6. // ['Taylor', 'Abigail'];

You may also specify how you wish the resulting list to be keyed:

  1. $array = array_pluck($array, 'developer.name', 'developer.id');
  2. // [1 => 'Taylor', 2 => 'Abigail'];

array_pull() {#collection-method}

array_pull 方法从数组中移除并返回一个键/值对:

  1. $array = ['name' => 'Desk', 'price' => 100];
  2. $name = array_pull($array, 'name');
  3. // $name: Desk
  4. // $array: ['price' => 100]

array_set() {#collection-method}

array_set 方法基于点号路径为一个深度嵌套的数组设置值:

  1. $array = ['products' => ['desk' => ['price' => 100]]];
  2. array_set($array, 'products.desk.price', 200);
  3. // ['products' => ['desk' => ['price' => 200]]]

array_sort() {#collection-method}

array_sort 方法依据给定闭包的返回值排序数组:

  1. $array = [
  2. ['name' => 'Desk'],
  3. ['name' => 'Chair'],
  4. ];
  5. $array = array_values(array_sort($array, function ($value) {
  6. return $value['name'];
  7. }));
  8. /*
  9. [
  10. ['name' => 'Chair'],
  11. ['name' => 'Desk'],
  12. ]
  13. */

array_sort_recursive() {#collection-method}

array_sort_recursive 方法用 sort 函数递归排序数组:

  1. $array = [
  2. [
  3. 'Roman',
  4. 'Taylor',
  5. 'Li',
  6. ],
  7. [
  8. 'PHP',
  9. 'Ruby',
  10. 'JavaScript',
  11. ],
  12. ];
  13. $array = array_sort_recursive($array);
  14. /*
  15. [
  16. [
  17. 'Li',
  18. 'Roman',
  19. 'Taylor',
  20. ],
  21. [
  22. 'JavaScript',
  23. 'PHP',
  24. 'Ruby',
  25. ]
  26. ];
  27. */

array_where() {#collection-method}

array_where 用给定闭包过滤数组:

  1. $array = [100, '200', 300, '400', 500];
  2. $array = array_where($array, function ($key, $value) {
  3. return is_string($value);
  4. });
  5. // [1 => 200, 3 => 400]

head() {#collection-method}

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

  1. $array = [100, 200, 300];
  2. $first = head($array);
  3. // 100

last() {#collection-method}

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

  1. $array = [100, 200, 300];
  2. $last = last($array);
  3. // 300

路径

app_path() {#collection-method}

app_path 函数返回 app 目录的绝对路径:

  1. $path = app_path();

你也可以用 app_path 函数来生成相对于应用目录的文件的绝对路径:

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

base_path() {#collection-method}

base_path 返回项目根目录的绝对路径:

  1. $path = base_path();

你也可以用 base_path 函数来生成相对于应用目录的文件的绝对路径:

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

config_path() {#collection-method}

config_path 函数返回应用配置目录的绝对路径:

  1. $path = config_path();

database_path() {#collection-method}

database_path 函数返回应用数据库目录的绝对路径:

  1. $path = database_path();

elixir() {#collection-method}

The elixir function gets the path to the versioned Elixir file:

  1. elixir($file);

public_path() {#collection-method}

public_path 函数返回 public 目录的绝对路径: function returns the fully qualified path to the public directory:

  1. $path = public_path();

storage_path() {#collection-method}

storage_path 函数返回 storage 目录的绝对路径: function returns the fully qualified path to the storage directory:

  1. $path = storage_path();

你也可以用 storage_path 函数来生成相对于storage目录的文件的绝对路径:

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

字串

camel_case() {#collection-method}

camel_case 函数将给定字串转换为驼峰式:

  1. $camel = camel_case('foo_bar');
  2. // fooBar

class_basename() {#collection-method}

class_basename 返回删除了名字空间的类名:

  1. $class = class_basename('Foo\Bar\Baz');
  2. // Baz

e() {#collection-method}

e 函数为给定的字串调用 htmlentities

  1. echo e('<html>foo</html>');
  2. // &lt;html&gt;foo&lt;/html&gt;

ends_with() {#collection-method}

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

  1. $value = ends_with('This is my name', 'name');
  2. // true

snake_case() {#collection-method}

snake_case 将给定字串转换为蛇形式:

  1. $snake = snake_case('fooBar');
  2. // foo_bar

str_limit() {#collection-method}

str_limit 函数限制一个字符串的长度。该函数接收一个字符串作为第一个参数,最大长度作为第二个参数:

  1. $value = str_limit('The PHP framework for web artisans.', 7);
  2. // The PHP...

starts_with() {#collection-method}

starts_with 函数判断字串是否以给定值开头:

  1. $value = starts_with('This is my name', 'This');
  2. // true

str_contains() {#collection-method}

str_contains 判断字串是否包含给定值:

  1. $value = str_contains('This is my name', 'my');
  2. // true

str_finish() {#collection-method}

str_finish 函数为字串添加给定单例:

  1. $string = str_finish('this/string', '/');
  2. // this/string/

str_is() {#collection-method}

str_is 函数判断字串是否匹配给定形式。星号表示通配符:

  1. $value = str_is('foo*', 'foobar');
  2. // true
  3. $value = str_is('baz*', 'foobar');
  4. // false

str_plural() {#collection-method}

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

  1. $plural = str_plural('car');
  2. // cars
  3. $plural = str_plural('child');
  4. // children

You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:

  1. $plural = str_plural('child', 2);
  2. // children
  3. $plural = str_plural('child', 1);
  4. // child

str_random() {#collection-method}

str_random 函数生成指定长度的随机字符串:

  1. $string = str_random(40);

str_singular() {#collection-method}

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

  1. $singular = str_singular('cars');
  2. // car

str_slug() {#collection-method}

str_slug 函数将字串转换为URL友好型: function generates a URL friendly “slug” from the given string:

  1. $title = str_slug("Laravel 5 Framework", "-");
  2. // laravel-5-framework

studly_case() {#collection-method}

studly_case 函数将字串转换为 StudlyCase 型:

  1. $value = studly_case('foo_bar');
  2. // FooBar

trans() {#collection-method}

trans 函数使用你的 本地化文件 翻译给定的语句:

  1. echo trans('validation.required'):

trans_choice() {#collection-method}

trans_choice 函数随词形变化翻译给定的语句:

  1. $value = trans_choice('foo.bar', $count);

URL

action() {#collection-method}

action 函数为给定控制器动作生成URL。无需给控制器传入完整的名字空间。相反,传入相对于 App\Http\Controllers 名字空间的控制器类名:

  1. $url = action('HomeController@getIndex');

如果方法接收路由参数,可以将它们作为第二个参数传入该函数:

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

asset() {#collection-method}

Generate a URL for an asset using the current scheme of the request (HTTP or HTTPS):

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

secure_asset() {#collection-method}

Generate a URL for an asset using HTTPS:

  1. echo secure_asset('foo/bar.zip', $title, $attributes = []);

route() {#collection-method}

route 函数为给定名称的路由生成URL:

  1. $url = route('routeName');

如果路由接收参数,可以将它们作为第二个参数传入该函数:

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

url() {#collection-method}

url 函数为给定路径生成绝对URL:

  1. echo url('user/profile');
  2. echo url('user/profile', [1]);

其他

auth() {#collection-method}

auth 函数返回一个认正器实例。可用来简化使用 Auth facade:

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

back() {#collection-method}

back() 函数为用户的前一个位置生成一个重定向响应:

  1. return back();

bcrypt() {#collection-method}

bcrypt 函数使用Bcrypt计算给定值的哈希值。可用来替换使用 Hash 门面:

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

collect() {#collection-method}

The collect function creates a collection instance from the supplied items:

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

config() {#collection-method}

config 函数获取配置变量的值。可用点号语法(包含文件名和你希望访问的选项)访问配置值。必须指定默认值,它将在配置项不存在时返回:

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

The config helper may also be used to set configuration variables at runtime by passing an array of key / value pairs:

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

csrf_field() {#collection-method}

csrf_field 生成一个包含CSRF令牌的HTML隐藏 input 。例如,使用 Blade 语法:

  1. {!! csrf_field() !!}

csrf_token() {#collection-method}

csrf_token 函数取回当前CSRF令牌值:

  1. $token = csrf_token();

dd() {#collection-method}

dd 函数输出给定变量然后结束脚本的执行:

  1. dd($value);

env() {#collection-method}

env 函数获取一个环境变量的值或者返回默认值:

  1. $env = env('APP_ENV');
  2. // 如果变量不存在,返回默认值
  3. $env = env('APP_ENV', 'production');

event() {#collection-method}

event 函数分派给定的 event 到其监听器:

  1. event(new UserRegistered($user));

factory() {#collection-method}

factory 函数为给定类创建一个模型工厂。当在 testingseeding 时可使用:

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

method_field() {#collection-method}

method_field 函数生成一个包含表单HTTP谓词假值的HTML hidden input域。例如,使用 Blade 语法:

  1. <form method="POST">
  2. {!! method_field('delete') !!}
  3. </form>

old() {#collection-method}

old 函数用于 取回 一个闪存入 session 的旧输入值:

  1. $value = old('value');

redirect() {#collection-method}

redirect 函数返回一个重定向器的实例来进行 重定向:

  1. return redirect('/home');

request() {#collection-method}

The request function returns the current request instance or obtains an input item:

  1. $request = request();
  2. $value = request('key', $default = null)

response() {#collection-method}

response 函数创建一个 响应 实例或者从响应工厂取得一个实例:

  1. return response('Hello World', 200, $headers);
  2. return response()->json(['foo' => 'bar'], 200, $headers);

session() {#collection-method}

The session function may be used to get / set a session value:

  1. $value = session('key');

You may set values by passing an array of key / value pairs to the function:

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

The session store will be returned if no value is passed to the function:

  1. $value = session()->get('key');
  2. session()->put('key', $value);

value() {#collection-method}

value 函数将简单地返回你给它的值。然后,如果为它传入一个 ClosureClosure 将被执行然后返回它的结果:

  1. $value = value(function() { return 'bar'; });

view() {#collection-method}

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

  1. return view('auth.login');

with() {#collection-method}

with 函数返回你给它的值。这个函数主要对本不可能的链式操作十分有用。

  1. $value = with(new Foo)->work();