Laravel 13 辅助函数完全手册 Laravel 提供了丰富的辅助函数,帮助开发者快速完成常见任务。本文将全面介绍 Laravel 13 中可用的辅助函数及其最佳实践。
数组函数 数组访问 1 2 3 4 5 6 7 8 9 10 $array = ['products' => ['desk' => ['price' => 100 ]]];$value = array_get ($array , 'products.desk.price' ); $value = array_get ($array , 'products.desk.discount' , 0 ); array_set ($array , 'products.desk.price' , 200 );array_set ($array , 'products.desk.color' , 'black' );array_has ($array , 'products.desk' ); array_has ($array , 'products.chair' );
数组操作 1 2 3 4 5 6 7 8 9 10 $array = ['name' => 'Desk' , 'price' => 100 ];array_only ($array , ['name' ]); array_except ($array , ['price' ]); $array = [100 , 200 , 300 ];array_first ($array , fn($value ) => $value >= 150 ); array_last ($array , fn($value ) => $value >= 150 ); array_pluck ([['name' => 'Desk' ], ['name' => 'Chair' ]], 'name' );
数组转换 1 2 3 4 5 6 7 $array = ['name' => 'Desk' , 'price' => 100 ];array_keys_to_camel (['first_name' => 'John' ]); array_keys_to_snake (['firstName' => 'John' ]); array_collapse ([[1 , 2 ], [3 , 4 ]]); array_flatten (['name' => 'Joe' , 'languages' => ['PHP' , 'Ruby' ]]);
数组分组与排序 1 2 3 4 5 6 7 8 9 10 11 $users = [ ['name' => 'John' , 'role' => 'admin' ], ['name' => 'Jane' , 'role' => 'user' ], ['name' => 'Bob' , 'role' => 'admin' ], ]; array_group_by ($users , 'role' );array_sort_by ($users , 'name' );array_sort_by_desc ($users , 'name' );
字符串函数 基础字符串操作 1 2 3 4 5 6 7 8 9 str_after ('This is a test' , 'This is' ); str_before ('This is a test' , 'test' ); str_between ('This is a test' , 'This' , 'test' ); str_contains ('This is a test' , 'is' ); str_contains ('This is a test' , ['is' , 'test' ]); str_starts_with ('This is a test' , 'This' ); str_ends_with ('This is a test' , 'test' );
字符串转换 1 2 3 4 5 6 7 8 9 10 11 str_camel ('foo_bar' ); str_snake ('fooBar' ); str_kebab ('fooBar' ); str_studly ('foo_bar' ); str_title ('foo bar' ); str_slug ('Laravel 13 Framework' , '-' ); str_lower ('HELLO' ); str_upper ('hello' ); str_ucfirst ('hello world' ); str_ucsplit ('HelloWorld' );
字符串处理 1 2 3 4 5 6 7 8 9 10 11 str_limit ('The quick brown fox jumps over the lazy dog' , 20 ); str_words ('The quick brown fox' , 3 ); str_word_count ('The quick brown fox' ); str_replace_first ('the' , 'a' , 'the quick the fox' ); str_replace_last ('the' , 'a' , 'the quick the fox' ); str_random (16 ); str_random_bytes (32 ); str_uuid (); str_ulid ();
字符串匹配 1 2 3 4 5 6 7 str_is ('foo*' , 'foobar' ); str_is ('ba*' , 'foobar' ); str_match ('/\d+/' , 'User 123' ); str_match_all ('/\d+/' , 'User 123, ID 456' ); str_replace_array ('?' , ['1' , '2' , '3' ], '?/?/?' );
Stringable 链式操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 use Illuminate \Support \Str ;$string = Str ::of (' Laravel Framework ' ) ->trim () ->lower () ->replace (' ' , '-' ) ->slug () ->limit (15 ); Str ::of ('Laravel Framework' ) ->words (2 , '...' ) ->title (); Str ::of ('{"name":"John"}' ) ->jsonDecode () ->get ('name' );
路径函数 1 2 3 4 5 6 7 8 9 10 11 base_path (); app_path (); config_path (); database_path (); lang_path (); public_path (); resource_path (); storage_path (); base_path ('vendor/bin' ); app_path ('Http/Controllers' );
URL 函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 url ('/users' ); url ('/users' , ['sort' => 'name' ]); url ()->current (); url ()->full (); url ()->previous (); route ('users.show' , ['user' => 1 ]); route ('users.index' , ['page' => 2 ], false ); action ([UserController ::class , 'index' ]); action ([UserController ::class , 'show' ], ['user' => 1 ]);asset ('images/logo.png' ); secure_asset ('images/logo.png' );
安全函数 1 2 3 4 5 6 7 8 9 10 11 bcrypt ('secret' ); hash ('sha256' , 'data' ); csrf_token (); csrf_field (); encrypt ('secret' ); decrypt ($encrypted ); old ('email' ); old ('email' , 'default@example.com' );
认证函数 1 2 3 4 5 6 7 8 9 auth (); auth ()->user (); auth ()->id (); auth ()->check (); auth ()->guest (); auth ('admin' )->user (); auth ()->login ($user ); auth ()->logout ();
缓存函数 1 2 3 4 5 6 cache ('key' ); cache ('key' , 'default' ); cache (['key' => 'value' ], 3600 ); cache ()->remember ('users' , 3600 , fn() => User ::all ());cache ()->forget ('key' );cache ()->flush ();
Cookie 函数 1 2 3 4 cookie ('name' , 'value' , 60 ); cookie ('name' , 'value' , 60 , '/' , null , true , true ); request ()->cookie ('name' );
数据库函数 1 2 3 4 5 6 7 8 9 10 11 db (); db ()->table ('users' )->get ();db ()->connection ('mysql' )->table ('users' )->get ();db ()->transaction (function () { }); db ()->beginTransaction ();db ()->commit ();db ()->rollBack ();
事件函数 1 2 3 event (new UserRegistered ($user )); event ('user.registered' , [$user ]);
日志函数 1 2 3 4 info ('User logged in' , ['id' => 1 ]);logger ('Debug message' );logger ()->error ('Error occurred' , ['exception' => $e ]);logger ()->channel ('slack' )->info ('Alert!' );
邮件函数 1 2 mail (new OrderShipped ($order ));mail ($user , new WelcomeEmail ());
模型函数 1 2 3 4 5 6 7 8 9 10 11 12 user (); user ('admin' ); optional ($user )->name; optional (null )->name; throw_if ($condition , new Exception ('Error' ));throw_unless ($condition , new Exception ('Error' ));retry (3 , function () { return Http ::get ('https://example.com' ); }, 100 );
响应函数 1 2 3 4 5 6 7 8 9 10 11 12 response ('Hello' , 200 );response ()->json (['name' => 'John' ]);response ()->download ($file );response ()->stream ($callback , 200 , $headers );redirect ('/home' );redirect ()->route ('home' );redirect ()->back ();redirect ()->action ([HomeController ::class , 'index' ]);view ('welcome' );view ('users.index' , ['users' => $users ]);
集合函数 1 2 3 4 5 collect ([1 , 2 , 3 ]); collect (['name' => 'John' , 'age' => 30 ]); collect ([1 , 2 , 3 ])->map (fn($n ) => $n * 2 ); collect ([1 , 2 , 3 ])->filter (fn($n ) => $n > 1 );
视图函数 1 2 3 4 view ('welcome' );view ('layouts.app' );view ()->exists ('emails.welcome' ); view ()->share ('key' , 'value' );
其他实用函数 环境与配置 1 2 3 4 5 6 7 8 9 10 11 12 app (); app ('config' ); app ()->environment (); app ()->environment ('local' ); app ()->environment (['local' , 'testing' ]); config ('app.timezone' );config ('app.name' , 'Laravel' ); config (['app.debug' => true ]); env ('APP_DEBUG' , false );env ('DB_HOST' , 'localhost' );
调试函数 1 2 3 4 5 6 7 dd ($value ); dump ($value ); ray ($value ); report ($exception ); report_if ($condition , $exception );
请求函数 1 2 3 4 5 6 7 8 9 10 11 12 request (); request ('name' ); request ('name' , 'default' ); request ()->all (); request ()->only (['name' , 'email' ]);request ()->except (['password' ]);request ()->file ('avatar' );request ()->has ('name' );request ()->filled ('name' );request ()->method (); request ()->isMethod ('post' );request ()->wantsJson ();
会话函数 1 2 3 4 5 6 session ('key' ); session ('key' , 'default' ); session (['key' => 'value' ]); session ()->flash ('status' , 'Task completed!' );session ()->reflash (); session ()->forget ('key' );
翻译函数 1 2 3 4 5 __ ('Welcome' ); __ ('messages.welcome' ); __ ('messages.welcome' , ['name' => 'John' ]); trans ('messages.welcome' );trans_choice ('messages.apples' , 10 );
验证函数 1 2 3 4 validator ($data , $rules );validator ($data , $rules )->validate ();validated ($data , $rules );
创建自定义辅助函数 定义辅助函数文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <?php if (!function_exists ('format_currency' )) { function format_currency ($amount , $currency = 'USD' ): string { $formatter = new NumberFormatter ('en_US' , NumberFormatter ::CURRENCY ); return $formatter ->formatCurrency ($amount , $currency ); } } if (!function_exists ('user_can' )) { function user_can ($ability , $arguments = [] ): bool { return auth ()->user ()?->can ($ability , $arguments ) ?? false ; } }
自动加载配置 1 2 3 4 5 6 7 { "autoload" : { "files" : [ "app/helpers.php" ] } }
总结 Laravel 13 的辅助函数提供了:
快速便捷的数组操作 强大的字符串处理能力 简洁的路由和 URL 生成 完善的安全和认证支持 灵活的响应和视图处理 可扩展的自定义函数 熟练掌握这些辅助函数,可以大大提高开发效率,编写更简洁优雅的代码。