curtissaunders/laravel-helpers

为 Laravel 5 系列的辅助函数

v1.2.0 2019-12-04 16:28 UTC

README

Latest Stable Version Total Downloads Latest Unstable Version License

安装

本包需要 PHP 5.6+,并包含 Laravel 5 服务提供者。

通过 composer 安装时,请在 composer.json 中包含此包。

"curtissaunders/laravel-helpers": "^1.0"

运行 composer installcomposer update 以下载依赖项,或者您可以运行 composer require curtissaunders/laravel-helpers

Laravel 5 集成

要使用此包与 Laravel 5,请将 Helper 服务提供者添加到 app/config/app.php 中的服务提供者列表。

'providers' => [

  CurtisSaunders\LaravelHelpers\HelpersServiceProvider::class
          
];

可用的辅助函数

  • versioned_asset 将应用缓存破坏查询字符串到您的资产中。
  • concat 将字符串连接在一起
  • concat_ws 将字符串连接在一起,分隔符由第一个参数定义
  • generate_uuid 将生成一个有效的 RFC 4122 UUID
  • route_is/routeIs 将检查当前路由是否匹配传递的路由
  • query_log_to_sql 允许您将数据库查询记录到变量中,并将其输出以方便调试
  • combine_query 将查询与其绑定组合

versioned_asset 的示例:

{{ versioned_asset('images/photo.png') }}

输出

http://mysite.com/images/photo.png?v=392104829

concat 的示例:

{{ concat('John', 'Terry', 'Dave') }}

输出

John Terry Dave

concat_ws 的示例:

{{ concat_ws(' - ', 'John', 'Terry', 'Dave') }}

输出

John - Terry - Dave

generate_uuid 的示例:

{{ generate_uuid() }}

输出

e4eaaaf2-d142-11e1-b3e4-080027620cdd

当使用 generate_uuid 函数时,您能够生成有效的 RFC 1, 3, 4 和 5 版本。为了更改版本,只需将所需版本号作为第一个参数传递(默认为 1)。例如,要生成版本 4 的 Uuid,您可以这样做

{{ generate_uuid(4) }}

输出

25769c6c-d34d-4bfe-ba98-e0ee856f3e7a

对于版本 3 和 5,您还需要传递一个字符串作为第二个参数。该字符串被散列并用于生成 Uuid。例如

{{ generate_uuid(3, 'php.net') }}

输出

11a38b9a-b3da-360f-9353-a5a725514269

route_is() 或 routeIs() 的示例:

在 Laravel Blade 中显示的示例

@if(route_is('about.index'))
// Do something
@else
// Do something else
@endif

或者

@if(routeIs('about.index'))
// Do something
@else
// Do something else
@endif

您也可以通过传递一个数组作为第二个参数来检查特定参数。例如,您可能希望检查您是否在特定的产品类别中,以便将“active”类应用到链接上。考虑以下在循环分类链接时的示例

@foreach($categories as $category)
    <a href="{{ route('product.category', [$category->slug]) }}" class="{{ route_is('product.category', ['categorySlug' => $category->slug]) ? 'active' : '' }}">
        {{ $category->name }}    
    </a>
@endforeach

当您位于该链接对应的页面时,将应用“active”类。

查询_log_to_sql 的示例:

// Enable laravel's query log
DB::connection()->enableQueryLog();
 
... // Do database transactions ...
 
// Get all the queries ran since the query log was enabled
$queryLog = DB::getQueryLog();
 
// Combine the query logs ran with their bindings into the sql that was ran
$sqlQueries = query_log_to_sql($queryLog);
 
// Returns an array of all the sql queries ran with their bindings in place, useful for quick debugging
dd($sqlQueries);

组合查询的示例:

// Create a query using Eloquent
$eloquentQuery = UserModel::where('email', '=', 'user.name@example.com');
 
// Combine the Eloquent query sql and bindings into a query you can run in mysql
$sqlQuery = combine_query($eloquentQuery->toSql(), $eloquentQuery->getBindings());