fikrimi/laravel-helper

此包最新版本(v1)没有可用的许可证信息。

另一个 Laravel 辅助工具

v1 2020-02-07 23:48 UTC

This package is auto-updated.

Last update: 2024-09-16 02:36:41 UTC


README

这是我个人的 Laravel 辅助工具,并决定发布它,希望其中的一些能对某处的某人有所帮助。您可以全部使用,也可以仅使用自己的 HelperServiceProvider 并复制粘贴您需要的部分。如果您认为任何功能是多余的、愚蠢的或不可用的,请提出问题。

它由5个辅助组组成。

通用

array_keys_exists(array $keys, array $arr)

它验证多个键是否存在于数组中。所有键都必须存在,否则将返回false。

    $first = [
        'foo'    => 'foo',
        'bar'    => 'bar',
        'foobar' => 'foobar',
        'barfoo' => 'barfoo',
    ];

    array_keys_exists(['foo', 'bar'], $first); //true
    array_keys_exists(['foo', 'chill'], $first); //false

is_assoc(array $arr)

检查它是否是关联数组。

  ...

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

  $third = [
     1 => 'isone',
      2 => 'istwo',
  ];

  $fourth = [
      0 => 'isone',
      1 => 'istwo',
  ];


  is_assoc($first); //true
  is_assoc($second); //false
  is_assoc($third); //true
  is_assoc($fourth); //false

ddr()

"Debug and Die but Readable",就像 dd() 但它总是首先转换为数组。所以想象一下,当你想要调试模型时,它总是先调用 ->toArray(),这样你就可以像正常人一样阅读它,同时仍然享有 dd() 的好处,如折叠等。它适用于任何可转换为数组的东西(转换为数组)或任何其他东西(如 dd)。

dr()

就像上面的 ddr(),但不会退出。因此,您可以设置如下内容

  dr($param);

  ...
  $param = x;
  ...

  dr($param);
  // or ddr($param) to make it die

round_up($number, $per = 500)round_down($number, $per = 500)

$number 向上舍入到最近的 $per,我本应该将 $per 设置为可配置的,也许下次吧。

  round_up(10200, 500); // 10500
  round_up(910, 900); // 990

  round_down(10200, 500); // 10000
  round_down(910, 900); // 900

bind_sql(Illuminate\Database\Query\Builder\Builder $builder)

这个非常有用,用于调试。它就像 ->toSql() 但它会绑定所有必要的参数。它需要一个构建器,因此必须在查询执行之前使用(如在 ->first()->get() 之前)。

  User::select()
    ->where('id', 5)
    ->toSql();

  // SELECT * FROM `users` where `id` = ?

  $user = User::select()
    ->where('id', 5);

  bind_sql($user);


  // SELECT * FROM `users` where `id` = 5

但我的真正意图是实际使用它来处理子查询,想象一下您可以使用 JOIN 子查询,但仍然享有查询构建器的优势。

  $books = \App\Books::select([
    'author_id'
  ])
    ->selectRaw('COUNT(*) as release_count')
    ->where('release_date', '>=', '1990-01-01')
    ->groupBy('author_id');

  dd([
    \App\Author::select([
      'author_id'
    ])
      ->selectRaw('COUNT(release_count) as releases')
      ->join(DB::raw('(' . bind_sql($books) . ') as books'), 'author_id', 'authors.id')
      ->groupBy('company_id')
      ->get()
  ]);

在上面的示例中,我们尝试使用 Books 的子查询来尝试将其与作者连接,并再次按公司发布次数进行分组。这可能不是一个合适的例子,但您已经明白了,将查询构建器转换为 SQL 绑定形式,并与其他查询构建器进行原始连接。

array_insert_before(array $array, $key, array $new)

$key 前插入新元素

  $first = [
    'one', 'two', 'three',
  ];

  array_insert_before($first, 1, [
    'one and half',
  ]);

  // [
  // 'one',
  // 'one and half',
  // 'two,
  // 'three',
  // ]

表单

字符串

URL

任意