New Features in Laravel 10.4

|
| By Navneet Kaur

With the release of version 10.4, the Laravel team added the File::json() function, changed existing HasMany connections to HasOne relationships, added a new test response assertion, and more.

File::json() method
The File::json() function was added by Laravel 10.4 to make it easier to extract data encoded in JSON from files:
// Before
$contents = File::get('sample.json');
$data = json_decode($contents, true);
// After
$data = File::json('sample.json');

Assert unsupported media type
An assertion helper for the 415 Unsupported Media Type response status code was added by Laravel 10.4:
$response->assertUnsupportedMediaType();

Convert an existing HasMany to HasOne relationship
The conversion of a HasMany to a HasOne and a MorphMany to a MorphOne was made possible by Laravel 10.4.
In order to define two relationships, consider the following example:
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();
}
}

With this PR, you can now use the ->one() function to accomplish the following things instead:
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();
}
}

The HasMany, HasManyThrough, and MorphMany all provide one() function.
Create macroable method for paginationInformation
By defining a macro for paginationInformation in Laravel 10.4, it is now possible to customize pagination information without having to extend all base resources:

/** @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();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *