Laravel 提供了许多实用的辅助函数,这些函数可以帮助开发者更高效地编写代码。以下是一些常用的 Laravel 辅助函数:
base_path
$basePath = base_path();
echo $basePath; // 输出项目根目录的绝对路径
app_path
app
目录的路径。$appPath = app_path();
echo $appPath; // 输出 app 目录的绝对路径
config_path
$configPath = config_path();
echo $configPath; // 输出 config 目录的绝对路径
array_add
$array = ['name' => 'John'];
$newArray = array_add($array, 'age', 30);
print_r($newArray); // 输出 ['name' => 'John', 'age' => 30]
collect
Illuminate\Support\Collection
实例,方便进行链式操作。$collection = collect([1, 2, 3]);
$sum = $collection->sum();
echo $sum; // 输出 6
str_random
$randomString = str_random(10);
echo $randomString; // 输出一个长度为 10 的随机字符串
str_slug
$slug = str_slug('Laravel 辅助函数');
echo $slug; // 输出 laravel-辅助函数
dd
$data = ['name' => 'John', 'age' => 30];
dd($data); // 打印 $data 并终止脚本
dump
$number = 123;
dump($number);
echo '继续执行脚本';
config
// 获取配置值
$appName = config('app.name');
echo $appName; // 输出 app.php 配置文件中 name 的值
// 设置配置值
config(['app.name' => 'New App Name']);
route
// 假设定义了一个名为 'user.profile' 的路由
$url = route('user.profile', ['id' => 1]);
echo $url; // 输出该路由对应的 URL
now
Carbon
实例。$now = now();
echo $now->format('Y-m-d H:i:s'); // 输出当前时间的格式化字符串
today
Carbon
实例。$today = today();
echo $today->format('Y-m-d'); // 输出今天的日期