by jay patel
Laravel 5.7.13 was released on 7th Nov 2018 with some new collection methods and the ability to return an array of messages in a custom validation rule.
First, new empty collection methods were added, including whenEmpty, whenNotEmpty, unlessEmpty, and unlessNotEmpty. For example, the whenEmpty method will fire this callback on an empty collection:
use Illuminate\Support\Collection ;
$collection = new Collection ;
$collection ->whenEmpty ( function ($collection) {
return $collection->push ( 'adam' ) ;
} ) ;
$this ->assertSame ( [ 'adam' ] , $collection ->toArray ( ) ) ;
The unless* behave the opposite way:
use Illuminate\Support\Collection ;
$collection = new Collection ;
$collection ->unlessEmpty ( function ( $collection ) {
return $collection ->push ( 'adam' ) ;
} ) ;
$this ->assertSame ( [ ] , $collection ->toArray ( ) ) ;
If the collection isn’t empty, the unlessEmpty closure is called:
use Illuminate\Support\Collection ;
$collection = new Collection ( [ ' user1 ' , ' user2 ' ] ) ;
$collection-> unlessEmpty ( function ( $collection ) {
return $collection ->push ( ' user3 ' ) ;
} ) ;
$this ->assertSame ( [ ' user1 ' , ' user2 ' , ' user3 ' ] , $collection ->toArray ( ) ) ;
Next, the ability to add an array of validation messages to custom validation rules was added. In a custom validation rule, you can return an array of messages like so:
public function message ( )
{
return [
' :attribute must be taylor ' ,
' :attribute must be a first name '
] ;
}
You can see the full diff between 5.7.12 and 5.7.13 on GitHub
Your email address will not be published. Required fields are marked *