# Query Builder pipe() Method
12.4 新增 pipe() method
- 定義在特定 model,且只有該 model 可重複使用時,使用 scope
- 不一定要定義在 model,可定義在單獨 class,且可在多個 model 中 reuse,使用 tap
- 不單純修改 query,而是回傳執行結果,使用 pipe
<?php
$records = DB::query()
->from('...')
// ...
->tap(new TappableScope) // returns the query
->pipe(new ActionScope); // executes the query and returns the result
# Skipping Migrations
12.4 新增 shouldRun() method,可決定該 migration 是否執行
<?php
return new class extends Migration
{
public function shouldRun()
{
return Feature::active(Flights::class);
}
// ...
}
# Arr::sole() Method
12.4 新增 Arr::sole(),只可且必須回傳單一結果,否則都會 throw error
<?php
Arr::sole(['foo']); // "foo"
// @throws \Illuminate\Support\ItemNotFoundException
Arr::sole(['foo'], fn (string $value) => $value === 'baz');
// @throws \Illuminate\Support\MultipleItemsFoundException
Arr::sole(['baz', 'foo', 'baz'], fn (string $value) => $value === 'baz');
# Queue fake Helper for Listeners Pushed
12.4 新增 Queue::listenersPushed(),可以 assert 特定 listener 有被觸發
<?php
Queue::fake();
event(new SomeEvent(value: 'look, a value!'));
$this->assertCount(
1,
Queue::listenersPushed(
SomeEventListener::class,
fn (SomeEvent $event) => $event->value === 'look, a value!'
)
);
# Model except() Method
12.4 新增 Model::except(),Model::only() 的相反,撈出不包含指定 column 的其他所有的 column
<?php
$user->except('id', 'email');
# Assert Does Not Throw Method
12.4 新增 assetDoesntThrow(),assert 指定區塊程式碼沒有 throw exception
<?php
$this->assertDoesntThrow(fn () => (new ProcessOrder)->execute());
# Where Null and Where Not Null JSON Assertions
12.4 AssertableJson 新增 whereNull() & whereNotNull(),語意上的話,我認為 assertNull & assertNotNull 是比較精準的命名
<?php
// Usage:
fn (AssertableJson $json) => $json->whereNull('error')
// Example from the Framework tests:
$assert = AssertableJson::fromArray([
'bar' => 'value',
]);
$this->expectException(AssertionFailedError::class);
$this->expectExceptionMessage('Property [bar] should be null.');
$assert->whereNull('bar');
# Eloquent Cast for HTML Strings in Laravel
12.4 新增,可將 Eloquent Attributes cast 為 AsHtmlString,AsHtmlString 可用在 Blade,當 Blade 渲染 HtmlString 時不會 escape,會原樣輸出,也適合用來將 HTML 儲存在 DB 當中
<?php
{{-- Warning: not be escaped when rendered in blade templates! --}}
{{ $model->html }}
使用方法
<?php
use Illuminate\Database\Eloquent\Casts\AsHtmlString;
protected function casts(): array
{
return [
'myAttribute' => AsHtmlString::class,
];
}
// Using the cast automatically does this
$model->myAttribute; // \Illuminate\Support\HtmlString
之前必須要額外手動轉換
<?php
protected function html(): Attribute
{
return Attribute::make(
get: fn (string $value) => str($value)->toHtmlString(),
);
}
// Using the html() accessor
$model->html; // HtmlString
// Or manually
$myString = new HtmlString($model->myString);
$myString = str($model->myString)->toHtmlString();