编程

Laravel 10.4 发布

566 2023-03-24 17:04:00

Laravel 团队发布了 v10.4 版本,其中涉及的新特性和变更包括: File::json 方法、将已有的 HasMany 关联转换成 HasOne 关联、一个新的响应断言等。

File::json() 方法

Austin White 贡献了 File::json() 方法,可以快速从文件中获取 JSON 格式的数据:

// 此前
$contents = File::get('sample.json');
$data = json_decode($contents, true);
// 此后
$data = File::json('sample.json');

断言支持媒体类型

Shamimul Alam 贡献了一个断言 helper,用于 415 Unsupported Media Type(415 - 不支持的媒体类型)的响应状态码:

$response->assertUnsupportedMediaType();

将现有的 HasMany 转换成 Hasone

Luke Kuzmish 贡献了将 HasMany 转换成 HasOne、MorphMany 转成 MorphOne 的支持。

下例不得不定义两个关联:

class User extends Model
{
    public function logins(): HasMany {
        return $this->hasMany(Login::class, 'some_id', 'the_other_id');
    }
    public function latestLogin(): HasOne {
        return $this->hasOne(Login::class, 'some_id', 'the_other_id')->latestOfMany();
    }
}

而现在,你可以使用 ->one() 方法实现:

class User extends Model
{
    public function logins(): HasMany {
        return $this->hasMany(Login::class, 'some_id', 'the_other_id');
    }
    public function latestLogin(): HasOne {
        return $this->logins()->one()->latestOfMany();
    }
}

这一 one() 方法在 HasMany, HasManyThrough 和 MorphMany 上都是可用的。

为paginationInformation(分页信息)创建macroable方法

Frans Slabbekoorn 贡献了为 paginationInformation 定义宏的支持,可以在无需从基类资源中为所有资源进行扩展的情况下,自定义分页信息:

/** @mixin \Illuminate\Http\Resources\Json\ResourceCollection */
class ResourceCollectionMixin
{
    public function paginationInformation(): Closure
    {
        return fn ($request, $paginated, $default) => collect($default)->mapWithKeysRecursively(fn ($item, $key) => [Str::camel($key) => $item])->toArray();
    }
}

Release Notes

You can see the complete list of new features and updates below and the diff between 10.3.0 and 10.4.0 on GitHub. The following release notes are directly from the changelog:

v10.4.0

Added

  • Added Illuminate/Testing/Concerns/AssertsStatusCodes::assertUnsupportedMediaType() (#46426)
  • Added curl_error_code: 77 to DetectsLostConnections (#46429)
  • Allow for converting a HasMany to HasOne && MorphMany to MorphOne (#46443)
  • Add option to create macroable method for paginationInformation (#46461)
  • Added Illuminate/Filesystem/Filesystem::json() (#46481)

Fixed

  • Fix parsed input arguments for command events using dispatcher rerouting (#46442)
  • Fix enums uses with optional implicit parameters (#46483)
  • Fix deprecations for embedded images in symfony mailer (#46488)

Changed

  • Added alternative database port in Postgres DSN (#46403)
  • Allow calling getControllerClass on closure-based routes (#46411)
  • Remove obsolete method_exists(ReflectionClass::class, 'isEnum') call (#46445)
  • Convert eloquent builder to base builder in whereExists (#46460)
  • Refactor shared static methodExcludedByOptions method to trait (#46498)