laravel 辅助函数

 数组&对象

1.array_divide()

array_divide 函数返回两个数组,一个包含原始数组的健,另一个包含原始数组的值
[$keys, $values] = array_divide(['name' => 'Desk']);
dd($keys, $values);

结果:

2.array_dot()

array_dot 函数将多维数组平铺到一维数组中,该数组使用「点」符号表示深度
$array = ['products' => ['desk' => ['price' => 100,'sum'=>10],'test'=>['price' => 1000,'sum'=>100]]];
$flattened = array_dot($array);
dd($flattened);

结果:

3.array_except()

array_except 函数从数组中删除给定的键/值对
$array = ['name' => 'Desk', 'price' => 100];
$filtered = array_except($array, ['name']);
dd($filtered);

结果:

4.array_first()

array_first 函数返回数组中第一个通过指定测试的元素
$array = [100, 200, 300];
$first = array_first($array, function ($value, $key) {
    return $value >= 150;
});
dd($first);

结果:

将默认值作为第三个参数传递给该方法。如果没有值通过测试,则返回该值:$first = array_first($array, $callback, $default);

5.array_flatten()

array_flatten 函数将多维数组平铺为一维数组
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby'=>'123']];
$flattened = array_flatten($array);
dd($flattened)

结果:

6.array_forget()

array_forget 函数使用「点」符号从深度嵌套数组中移除给定的键/值对
$array = ['products' => ['desk' => ['price' => 100]]];
array_forget($array, 'products.desk');
dd($array);
结果: 

7.array_get()

array_get 函数使用「点」符号从深度嵌套的数组中检索值
$array = ['products' => ['desk' => ['price' => 100]]];
$price = array_get($array, 'products.desk.price');
dd($price);
结果:

array_get 函数也接受一个默认值,如果没有找到指定的健,则返回该值:
$discount = array_get($array, 'products.desk.discount', 0);

8.array_only()

array_only 函数仅返回给定数组中指定的键/值对
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];
$slice = array_only($array, ['name', 'price']);
dd($slice);
结果:

9.array_pluck()

array_pluck 函数从数组中检索给定键的所有值
$array = [
            ['developer' => ['id' => 1, 'name' => 'Taylor']],
            ['developer' => ['id' => 2, 'name' => 'Abigail']],
        ];
$names = array_pluck($array, 'developer.name');
dd($names);

结果:

你也可以指定生成的列表的键

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

结果:

10.array_pull()

array_pull 函数返回并从数组中删除键/值对
$array = ['name' => 'Desk', 'price' => 100];
$name = array_pull($array, 'name');
dd($name,$array);

结果:

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

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

11.array_random()

array_random 函数从数组中返回一个随机值
$array = [1, 2, 3, 4, 5];
$random = array_random($array);
dd($random);

结果:

你也可以指定要返回的随机数的数量作为第二个可选参数。一旦你指定了第二个参数,即使数量为 1,这个函数也会返回一个数组
$array = [1, 2, 3, 4, 5];
$random = array_random($array,3);
dd($random);

结果:

12.array_where()

array_where 函数使用给定的闭包来过滤数组
$array = [100, '200', 300, '400', 500];
$filtered = array_where($array, function ($value, $key) {
            return is_string($value);
        });
dd($filtered);

结果:

13.data_get()

data_get 函数使用「点」符号从嵌套数组或对象中检索值
$data = ['products' => ['desk' => ['price' => 100]]];
$price = data_get($data, 'products.desk.price');
dd($price);

结果:

data_get 函数还接受默认值作为第三个参数,如果找不到指定的键,将返回该值

$discount = data_get($data, 'products.desk.discount', 0);

14.head() 函数返回给定数组中的第一个元素

15.last() 函数返回给定数组中的最后一个元素

16.app_path() 

app_path 返回 app 目录的完整路径。你还可以使用 app_path 函数来生成相对于 app 目录的文件完整路径
$path = app_path();
dd($path);

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

17.base_path() 

base_path 函数返回项目根目录的完整路径。你还可以使用 base_path 函数生成指定文件相对于项目根目录的完整路径
$path = base_path();
dd($path);

$path = base_path('vendor\bin');
dd($path);

18.config_path()  config_path 函数返回应用程序 config 目录的完整路径。你也可以使用 config_path 函数来生成应用程序配置目录中给定文件的完整路径

19.database_path()  database_path 函数返回应用程序 database 目录的完整路径。你也可以使用 database_path 函数来生成数据库目录中给定文件的完整路径

20.public_path()  public_path函数返回应用程序 public目录的完整路径。你也可以使用 public_path函数来生成public目录中给定文件的完整路径

21.resource_path()  函数返回应用程序 resource目录的完整路径。你也可以使用 resource_path函数来生成resource目录中给定文件的完整路径

21.storage_path()  函数返回应用程序 storage目录的完整路径。你也可以使用 storage_path函数来生成storage目录中给定文件的完整路径

 

字符串

1.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);
dd($replaced);

结果:

2.str_random()

str_random 函数生成一个指定长度的随机字符串。这个函数数用 PHP 的 random_bytes 函数
$random = str_random(30);
dd($random);

3.str_replace_array()

str_replace_array 函数使用数组顺序替换字符串中的给定值
$string = '该活动将于 ? 至 ? 之间举行';
$replaced = str_replace_array('?', ['8:30', '9:00'], $string);
dd($replaced);

URLs
action() action 函数为指定的控制器动作生成一个 URL。你不需要传递完整的控制器命名空间。只需要传递相对于 App\Http\Controllers 的命名空间的控制器类名称:
$url = action('HomeController@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() 如果给定的布尔表达式计算结果为 true, abort_if 函数将抛出一个 HTTP 异常: abort_if(! Auth::user()->isAdmin(), 403); 和 abort 方法一样,你也可以提供异常的响应文本作为第三个参数,并提供一个自定义响应头数组作为第四个参数。 abort_unless() 如果给定的布尔表达式计算结果为 false,abort_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'); $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 令牌值的 HTMLhidden 表单字段。例如,使用 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 函数。 encrypt() encrypt 函数使用 Laravel 的加密器对给定的值进行加密: $encrypted = encrypt($unencrypted_value); env() env 函数获取环境变量的值或者返回默认值: $env = env('APP_ENV'); // 如果环境变量不存在则返回默认值... $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('一些有用的信息!'); 有前后关系的数组也可以传递给函数: info('用户登录尝试失败。', ['id' => $user->id]); logger() logger 函数可以将一个 debug 级别的消息写入到日志中: logger('Debug 消息'); 有前后关系的数组也可以传递给函数: 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) !!} 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 () { // 在 100ms 左右尝试 5 次... }, 100); session() session 函数可以用来获取或者设置 Session 值: $value = session('key'); 你可以通过将一组键/值对传递给该函数来设置值: session(['chairs' => 7, 'instruments' => 3]); 如果没有传递值给函数,则返回 Session 实例: $value = session()->get('key'); session()->put('key', $value); tap() tap 函数接受两个参数:一个任意的 $value 和一个闭包。$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() 如果给定的值不为 blank 并且返回 Closure,那么 transform 函数对给定的值执行 Closure 并返回其结果: $callback = function ($value) { return $value * 2; }; $result = transform(5, $callback); // 10 默认值或 Closure 也可以作为方法的第三个参数传递。如果给定值为空白,则返回该值: $result = transform(null, $callback, 'The value is blank'); // The value is blank validator() validator 函数用给定的参数创建一个新的验证器实例。为方便起见,你可以使用它来代替 Validator facade : $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
posted @ 2018-12-07 18:34  心之所依  阅读(9646)  评论(0编辑  收藏  举报