laravel常用辅助函数和模板指令

数组

use Illuminate\Support\Arr;

Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Arr::flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);  // 将多维数组中数组的值取出平铺为一维数组 ['Joe', 'PHP', 'Ruby']
[$keys, $values] = Arr::divide(['name' => 'Desk']); //$keys: ['name']  $values: ['Desk']

Arr::except(['name' => 'Desk', 'price' => 100], ['price']);  //['name' => 'Desk']
Arr::only(['name' => 'Desk', 'price' => 100, 'orders' => 10], ['name', 'price']); // ['name' => 'Desk', 'price' => 100]
Arr::first([100, 200, 300], function ($value, $key) {
    return $value >= 150;
});// 200  Arr::first($array, $callback, $default);
Arr::last([100, 200, 300, 110], function ($value, $key) {
    return $value >= 150;
}); // 300  Arr::last($array, $callback, $default);
Arr::where([100, '200', 300, '400', 500], function ($value, $key) {
    return is_string($value);
}); // [1 => '200', 3 => '400']
Arr::whereNotNull([0, null]); // [0 => 0]
Arr::pluck([
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
], 'developer.name'); // ['Taylor', 'Abigail']
Arr::pluck([
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
], 'developer.name', 'developer.id');// [1 => 'Taylor', 2 => 'Abigail']
Arr::forget(['products' => ['desk' => ['price' => 100]]], 'products.desk');  //  ['products' => []]

Arr::get(['products' => ['desk' => ['price' => 100]]], 'products.desk.price'); // 100
Arr::get(['products' => ['desk' => ['price' => 100]]], 'products.desk.discount', 0); // 0
Arr::has(['product' => ['name' => 'Desk', 'price' => 100]], 'product.name'); // true
Arr::has(['product' => ['name' => 'Desk', 'price' => 100]], ['product.price', 'product.discount']); // false
Arr::hasAny(['product' => ['name' => 'Desk', 'price' => 100]], ['product.price', 'product.discount']); // true

Arr::query([
    'name' => 'Taylor',
    'order' => [
        'column' => 'created_at',
        'direction' => 'desc'
    ]
]); // name=Taylor&order[column]=created_at&order[direction]=desc
Arr::random([1, 2, 3, 4, 5]); //随机取一个
Arr::random([1, 2, 3, 4, 5], 2); //随机取2个  [2, 5]
Arr::dot(['products' => ['desk' => ['price' => 100]]]); //['products.desk.price' => 100]
Arr::undot([
    'user.name' => 'Kevin Malone',
    'user.occupation' => 'Accountant',
]);// ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]

data_fill(['products' => ['desk' => ['price' => 100]]], 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 100]]]
data_fill(['products' => ['desk' => ['price' => 100]]], 'products.desk.discount', 10); // ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
data_fill([
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2'],
    ],
], 'products.*.price', 200);
data_get(['products' => ['desk' => ['price' => 100]]], 'products.desk.price');  // 100
data_get(['products' => ['desk' => ['price' => 100]]], 'products.desk.discount', 0); // 0
data_get([
    'product-one' => ['name' => 'Desk 1', 'price' => 100],
    'product-two' => ['name' => 'Desk 2', 'price' => 150],
], '*.name');// ['Desk 1', 'Desk 2'];
data_set(['products' => ['desk' => ['price' => 100]]], 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 200]]]
data_set([
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2', 'price' => 150],
    ],
], 'products.*.price', 200);
data_set(['products' => ['desk' => ['price' => 100]]], 'products.desk.price', 200, $overwrite = false); // ['products' => ['desk' => ['price' => 100]]]

字符串

use Illuminate\Support\Str;

Str::after('This is my name', 'This is'); // ' my name'
Str::afterLast('App\Http\Controllers\Controller', '\\'); // 'Controller'
Str::before('This is my name', 'my name');  // 'This is '
Str::beforeLast('This is my name', 'is'); // 'This '
Str::between('This is my name', 'This', 'name'); // ' is my '

Str::contains('This is my name', 'my'); // true
Str::contains('This is my name', ['my', 'foo']); // true
Str::containsAll('This is my name', ['my', 'name']); // true
Str::startsWith('This is my name', 'This'); // true
Str::startsWith('This is my name', ['This', 'That', 'There']); // true
Str::endsWith('This is my name', 'name'); // true
Str::endsWith('This is my name', ['name', 'foo']); // true
Str::endsWith('This is my name', ['this', 'foo']); // false
//用来判断字符串是否与指定模式匹配
Str::is('foo*', 'foobar'); // true
Str::is('baz*', 'foobar'); // false

Str::studly('foo_bar'); // FooBar
Str::camel('foo_bar'); // fooBar
Str::snake('fooBar'); // foo_bar
Str::snake('fooBar', '-'); // foo-bar
Str::kebab('fooBar'); // foo-bar
Str::excerpt('This is my name', 'my', [
    'radius' => 3
]); // '...is my na...'  截断字符串
Str::excerpt('This is my name', 'name', [
    'radius' => 3,
    'omission' => '(...) '
]); // '(...) my name'
Str::limit('The quick brown fox jumps over the lazy dog', 20); // The quick brown fox...
Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); // The quick brown fox (...)
//将指定的字符串修改为以指定的值结尾的形式
Str::finish('this/string', '/'); // this/string/
Str::finish('this/string/', '/'); // this/string/
//将给定的值添加到字符串的开始位置
Str::start('this/string', '/'); // /this/string
Str::start('/this/string', '/'); // /this/string
//将由大小写、连字符或下划线分隔的字符串转换为空格分隔的字符串,同时保证每个单词的首字母大写
Str::headline('steve_jobs'); // Steve Jobs
Str::headline('EmailNotificationSent'); // Email Notification Sent

Str::ascii('û'); // 'u'  尝试将字符串转换为 ASCII 值
Str::isAscii('Taylor'); // true
Str::isAscii('ü'); // false
Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'); // true
Str::markdown('# Laravel'); // <h1>Laravel</h1>
Str::markdown('# Taylor <b>Otwell</b>', [
    'html_input' => 'strip',
]); // <h1>Taylor Otwell</h1>
//重复的字符掩盖字符串的一部分
Str::mask('taylor@example.com', '*', 3); // tay***************
Str::mask('taylor@example.com', '*', -15, 3); // tay***@example.com

Str::padBoth('James', 10, '_'); // '__James___'
Str::padBoth('James', 10); // '  James   '
Str::padLeft('James', 10, '-='); // '-=-=-James'
Str::padLeft('James', 10); // '     James'
Str::padRight('James', 10, '-'); // 'James-----'
Str::padRight('James', 10); // 'James     '
Str::plural('car'); // cars
Str::plural('child'); // children
Str::singular('cars'); // car
Str::remove('e', 'Peter Piper picked a peck of pickled peppers.'); // Ptr Pipr pickd a pck of pickld ppprs.
Str::replace('8.x', '9.x', 'Laravel 8.x'); // Laravel 9.x
Str::replaceArray('?', ['8:30', '9:00'], 'The event will take place between ? and ?'); // The event will take place between 8:30 and 9:00
Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog'); // a quick brown fox jumps over the lazy dog
Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog'); // the quick brown fox jumps over a lazy dog
Str::reverse('Hello World'); // dlroW olleH
Str::slug('Laravel 5 Framework', '-'); // laravel-5-framework 将给定的字符串生成一个 URL 友好的「slug」
Str::title('a nice title uses the correct case'); // A Nice Title Uses The Correct Case

Str::substrCount('If you like ice cream, you will like snow cones.', 'like'); // 2
Str::wordCount('Hello, world!'); // 2
Str::words('Perfectly balanced, as all things should be.', 3, ' >>>'); // Perfectly balanced, as >>>
Str::uuid();

Str::of('Taylor')
    ->when(true, function ($string) {
        return $string->append(' Otwell');
    }); // 'Taylor Otwell'
Str::of('tony stark')
    ->whenContains('tony', function ($string) {
        return $string->title();
    }); // 'Tony Stark'
Str::of('tony stark')
    ->whenContains(['tony', 'hulk'], function ($string) {
        return $string->title();
    }); // Tony Stark
Str::of('tony stark')
    ->whenContainsAll(['tony', 'stark'], function ($string) {
        return $string->title();
    }); // Tony Stark
Str::of('  ')->whenEmpty(function ($string) {
    return $string->trim()->prepend('Laravel');
}); // 'Laravel'
Str::of('Framework')->whenNotEmpty(function ($string) {
    return $string->prepend('Laravel ');
}); // 'Laravel Framework'
Str::of('disney world')->whenStartsWith('disney', function ($string) {
    return $string->title();
}); // 'Disney World'
Str::of('disney world')->whenEndsWith('world', function ($string) {
    return $string->title();
}); // 'Disney World'
Str::of('laravel')->whenExactly('laravel', function ($string) {
    return $string->title();
}); // 'Laravel'
Str::of('foo/bar')->whenIs('foo/*', function ($string) {
    return $string->append('/baz');
}); // 'foo/bar/baz'
Str::of('foo/bar')->whenIsAscii('laravel', function ($string) {
    return $string->title();
});// 'Laravel'

路径

public_path();
public_path('css/app.css');
resource_path();
resource_path('sass/app.scss');
storage_path();
storage_path('app/file.txt');

URL

action([UserController::class, 'profile'], ['id' => 1]);
asset('img/photo.jpg');
route('route.name');
route('route.name', ['id' => 1]);
url('user/profile', [1]);

认证

auth()->user();

$password = bcrypt('my-secret-password');

$encrypted = encrypt('my-secret-value');
$value = decrypt($encrypted);

值判断

blank(''); // true
blank('   '); // true
blank(null); // true
blank(collect()); // true
blank(0); // false
blank(true); // false
blank(false); // false

filled(0); // true
filled(true); // true
filled(false); // true
filled(''); // false
filled('   '); // false
filled(null); // false
filled(collect()); // false

缓存

cache('key');
cache('key', 'default');
cache(['key' => 'value'], 300);
cache(['key' => 'value'], now()->addSeconds(10));

集合

collect(['taylor', 'abigail']);
collect(['a', 'b'])->toArray(); // ['a', 'b']
collect(['a', 'b'])->toJson()‌;

collect([1, 2, 3])->filter(fn ($n) => $n > 1); // [2, 3]
collect([['name' => 'John'], ['name' => 'Jane']])->where('name', 'John'); // [['name' => 'John']]
collect([1, 2, 3])->first(); // 1
collect([1, 2, 3])->last(fn ($n) => $n < 3); // 2

collect([1, 2])->map(fn ($n) => $n * 2); // [2, 4]
collect([['id' => 1], ['id' => 2]])->pluck('id'); // [1, 2]
collect([['role' => 'admin'], ['role' => 'user']])->groupBy('role'); // ['admin' => [...], 'user' => [...]]

collect([1, 2, 3])->sum(); // 6
collect([['price' => 10], ['price' => 20]])->avg('price'); // 15
collect([5, 2, 8])->max(); // 8

collect([1, 2, 3, 4])->chunk(2); // [[1, 2], [3, 4]]
collect([[1, 2], [3]])->flatten(); // [1, 2, 3]
collect([1, 2])->merge([3, 4]); // [1, 2, 3, 4]

collect(['taylor', 'abigail', null])->map(function (?string $name) {
    return strtoupper($name);
})->reject(function (string $name) {
    return empty($name);
});

读写配置

config('app.timezone');
config('app.timezone', $default);

env('APP_ENV');
env('APP_ENV', 'production');

任务和事件

// 在控制器中分发任务
dispatch(new App\Jobs\SendEmails); //将给定的 任务 推送到 Laravel 任务队列

event(new UserRegistered($user)); //向监听器派发给定 事件

请求和响应

$request = request();
$value = request('key', $default);
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);

session


$value = session('key');
$value = session()->get('key');
session()->put('key', $value);
session(['chairs' => 7, 'instruments' => 3]);

日期时间

Illuminate\Support\Carbon 实例

$now = now(); 
$current = Carbon::now(); // 等效写法
$today = Carbon::today(); // 今天 00:00:00
$yesterday = Carbon::yesterday(); // 昨天 00:00:00
$tomorrow = Carbon::tomorrow(); // 明天 00:00:00

echo now()->toDateTimeString(); // "2022-09-01 10:21:09"
echo now()->toDateString();     // "2022-09-01"
echo now()->format('Y年m月d日 H:i'); // "2022年09月01日 10:21"

$nextWeek = now()->addWeek(); // 加1周
$prevHour = now()->subHour(); // 减1小时
$diffInDays = now()->diffInDays('2022-10-01'); // 计算与未来日期的天数差

now()->isWeekend()
$isFuture = now()->gt('2022-10-01'); // 检查是否晚于指定日期

$shanghaiTime = now()->setTimezone('Asia/Shanghai'); // 上海时区
echo now()->locale('zh_CN')->isoFormat('LLLL'); // "2022年9月1日星期一 10:21"

$orderTime = Carbon::parse('2022-09-10 18:00');
$remainingHours = now()->diffInHours($orderTime, false); // 剩余小时数(可为负)

模板指令

定义布局

//
<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show  // @show 则在定义的同时 立即 yield 这个片段

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

使用布局

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar')
    @parent   // @parent 指令向布局的 sidebar 追加(而非覆盖)内容

    <p>This is appended to the master sidebar.</p>
@endsection  // @endsection 指令仅定义了一个片段

@section('content')
    <p>This is my body content.</p>
@endsection

显示数据

// 将被 PHP 的 htmlspecialchars 函数自动转义以防范 XSS 攻击
{{ $name }}

//展示非转义数据
{!! $name !!}

// json 数据
<script>
    var app = @json($array);
</script>

Blade 指令

// php
@php
    //
@endphp

// If 语句
@if (count($records) === 1)
    // 有一条记录
@elseif (count($records) > 1)
    // 有多条记录
@else
    // 没有记录
@endif

//循环
@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping forever.</p>
@endwhile

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif
    <li>{{ $user->name }}</li>
    @if ($user->number == 5)
        @break
    @endif
@endforeach

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif
    @if ($loop->last)
        This is the last iteration.
    @endif
    <p>This is user {{ $user->id }}</p>
@endforeach
posted @ 2023-05-12 19:23  carol2014  阅读(385)  评论(0)    收藏  举报