Laravel Helpers
Installation
1.Install package through composer., (*1)
composer require tyler36/laravel-helper-macros
2.Add package to config/app.php
, (*2)
Tyler36\laravelHelpers\LaravelHelperServiceProvider::class,
Helpers
Validator
Inspired by Validate (almost) anything in Laravel.
Uses Laravel Validator class to validate anything., (*3)
EG. Validate Date (expects FALSE):, (*4)
tyler36\laravelHelpers\Helper::validate('20150230', 'date');
EG. Validate Date (expects TRUE):, (*5)
tyler36\laravelHelpers\Helper::validate('20150230', 'date');
Macros
Collections
These macros extend collection functionality., (*6)
pipe
Inspired by The pipe collection macro.
Pass collection to a function., (*7)
$collect = collect([1, 2, 3])
->pipe(function ($data) {
return $data->merge([4, 5, 6]);
});
dd
Inspired by Debugging collections.
Debug a collection by 'dump and die' the current state. Can be used mid-chain to break and dump., (*8)
collect($items)
->filter(function() {
...
})
->dd()
ifEmpty
Run callback if collection is empty., (*9)
$items = collect([]);
$items->ifEmpty(function(){
abort(500, 'No items');
});
ifAny
Run callback if collection has data ( >1 item)., (*10)
$errors = collect(['Something went wrong']);
$errors->ifAny(function(){
abort(500, 'There was at-least 1 problem');
});
mapToAssoc
Convert collection to associative array
Inspired by Customizing Keys When Mapping Collections, (*11)
$emailLookup = $employees->mapToAssoc(function ($employee) {
return [$employee['email'], $employee['name']];
});
Response
These macros help to standardize api json response returns throughout the application.
Inspired by Laravel Response Macros for APIs, (*12)
Success
Returns payload ($data) with a HTTP status code 200, (*13)
response()->success($data);
EG., (*14)
response()->success(['earth' => 3, 'sun' => 'yellow'])
Returns HTTP status 200 with the following:, (*15)
{"errors":false,"data":{"earth":3,"sun":"yellow"}}
noContent
Returns empty content with a HTTP status code 402, (*16)
response()->noContent()
Error
Returns message ($message) content with an optional HTTP status code ($statusCode) [Default: HTTP status code 400], (*17)
response()->error($message);
Eg., (*18)
response()->error('There was an error.');
Returns HTTP status 400 with the following:, (*19)
{"errors":true,"message":"There was an error."}
Eg., (*20)
response()->error('Not authorized!', 403);
Returns HTTP status 403 with the following:, (*21)
{"errors":true,"message":"Not authorized!"}