An extensive set of generic PHP and Laravel-specific helpers.
Each helper is optional and comes with instructions on how to use it.
- Requirements
- How to install
- Global helper functions
- Collection macros
- Class helpers
- Database table reader
- License
- Change log
- Testing
- Contributing
- Security
- Credits
- About
- PHP 7 or higher
- Laravel 5.4 or higher
Via Composer:
composer require sebastiaanluca/laravel-helpers
To use the global helper functions or enable the collection macros, add the corresponding service provider to your config/app.php
file:
'providers' => [
SebastiaanLuca\Helpers\Methods\GlobalHelpersServiceProvider::class,
SebastiaanLuca\Helpers\Collections\CollectionMacrosServiceProvider::class,
]
Other helpers are standalone and do not need to be activated beforehand.
Randomly return true
or false
.
rand_bool();
// true
Wrap a string with another string.
str_wrap('foo', '*');
// "*foo*"
Check if an array is associative.
Performs a simple check to determine if the given array's keys are numeric, start at 0, and count up to the amount of values it has.
is_assoc_array(['color' => 'blue', 'age' => 31]);
// true
is_assoc_array([0 => 'blue', 7 => 31]);
// true
is_assoc_array(['blue', 31]);
// false
is_assoc_array([0 => 'blue', 1 => 31]);
// false
Expand a flat dotted array into a multi-dimensional associative array.
If a key is encountered that is already present and the existing value is an array, each new value will be added to that array. If it's not an array, each new value will override the existing one.
array_expand(['products.desk.price' => 200]);
/*
[
"products" => [
"desk" => [
"price" => 200,
],
],
]
*/
Get the array without the given values.
Accepts either an array or a value as parameter to remove.
$cars = ['bmw', 'mercedes', 'audi'];
$soldOut = ['audi', 'bmw'];
$inStock = array_without($cars, $soldOut);
// ["mercedes"]
array_without(['one', 'two', 'three'], 'two');
// ["one", "three"]
Pull a single value from a given array.
Returns the given value if it was successfully removed from the source array or null
if it was not found.
$source = ['A', 'B', 'C'];
$removed = array_pull_value($source, 'C');
// $removed = "C"
// $source = ["A", "B"]
Pull an array of values from a given array.
Returns the values that were successfully removed from the source array or an empty array if none were found.
$source = ['A', 'B', 'C'];
$removed = array_pull_values($source, ['A', 'B']);
// $removed = ["A", "B"]
// $source = ["C"]
Create a unique string identifier for an array.
The identifier will be entirely unique for each combination of keys and values.
array_hash([1, 2, 3]);
// "262bbc0aa0dc62a93e350f1f7df792b9"
array_hash(['hash' => 'me']);
// "f712e79b502bda09a970e2d4d47e3f88"
Create a unique string identifier for an object.
Similar to array_hash, this uses serialize
to stringify all public properties first. The identifier will be entirely unique based on the object class, properties, and its values.
class ValueObject {
public $property = 'randomvalue';
}
object_hash(new ValueObject);
// "f39eaea7a1cf45f5a0c813d71b5f2f57"
Check if a class has a certain public method.
class Hitchhiker {
public function answer() {
return 42;
}
}
has_public_method(Hitchhiker::class, 'answer');
// true
has_public_method(new Hitchhiker, 'answer');
// true
Create a Carbon datetime object from a string.
Requires the nesbot/carbon package.
carbonize('2017-01-18 11:30');
/*
Carbon\Carbon {
"date": "2017-01-18 11:30:00.000000",
"timezone_type": 3,
"timezone": "UTC",
}
*/
Create a new pipe item from a given value.
Allows you to chain method calls any way you see fit. See the enabling PHP method chaining with a makeshift pipe operator blog post for more info.
take('https://blog.sebastiaanluca.com/')
->pipe('parse_url', PHP_URL_HOST)
->pipe('explode', '.', '$$')
->pipe('reset')
->get();
// "blog"
Get the active app locale or the fallback locale if it's missing or not set.
Requires the laravel/framework package.
locale();
// "en"
Display structured debug information about one or more values in plain text using Kint and halt script execution afterwards. Accepts multiple arguments to dump.
Output will be identical to ddd
when used in a command line interface. In a browser, it'll display plain, but structured text.
Requires the kint-php/kint package.
sss('string');
/*
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
string (6) "string"
═══════════════════════════════════════════
Called from .../src/MyClass.php:42
*/
sss('string', 0.42, ['array']);
/*
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
string (6) "string"
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
double 0.42
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
array (1) [
0 => string (5) "array"
]
═══════════════════════════════════════════
Called from .../src/MyClass.php:42
*/
Display structured debug information about one or more values using Kint and halt script execution afterwards. Accepts multiple arguments to dump. Output will be identical to sss
when used in a command line interface. In a browser, it'll display an interactive, structured tree-view.
Requires the kint-php/kint package.
See the sss helper for example output.
Display structured debug information about one or more values in plain text using Kint and halt script execution afterwards, but only if the condition is truthy. Does nothing if falsy. Accepts multiple arguments to dump.
Requires the kint-php/kint package.
sss_if($user->last_name, 'User has a last name', $user->last_name);
See the sss helper for example output.
Display structured debug information about one or more values using Kint and halt script execution afterwards, but only if the condition is truthy. Does nothing if falsy. Accepts multiple arguments to dump.
Requires the kint-php/kint package.
ddd_if(app()->environment('local'), 'Debugging in a local environment!');
See the ddd helper for example output.
Create Carbon instances from items in a collection.
Requires the nesbot/carbon package.
collect([
'yesterday',
'tomorrow',
'2017-07-01',
])->carbonize();
/*
Illuminate\Support\Collection {
all: [
Carbon\Carbon {
"date": "2017-07-09 00:00:00.000000",
"timezone_type": 3,
"timezone": "UTC",
},
Carbon\Carbon {
"date": "2017-07-11 00:00:00.000000",
"timezone_type": 3,
"timezone": "UTC",
},
Carbon\Carbon {
"date": "2017-07-01 00:00:00.000000",
"timezone_type": 3,
"timezone": "UTC",
},
],
}
*/
Reduce each collection item to the value found between a given start and end string.
The second parameter is optional and falls back to the start string if null
.
collect([
'"value1"',
'"value2"',
'"value3"',
])->between('"', '"');
/*
Illuminate\Support\Collection {
all: [
"value1",
"value2",
"value3",
],
}
*/
Perform an operation on the collection's keys.
The callable operation can either be a globally available method or a closure.
collect([
'a' => 'value',
'b' => 'value',
'c' => 'value',
])->transformKeys('strtoupper');
/*
Illuminate\Support\Collection {
all: [
"A" => "value",
"B" => "value",
"C" => "value",
],
}
*/
collect([
'a' => 'value',
'b' => 'value',
'c' => 'value',
])->transformKeys(function (string $key) {
return 'prefix-' . $key;
});
/*
Illuminate\Support\Collection {
all: [
"prefix-a" => "value",
"prefix-b" => "value",
"prefix-c" => "value",
],
}
*/
Transpose (flip) a collection matrix (array of arrays) so its columns become rows and its rows become columns.
collect([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])->transpose();
/*
Illuminate\Support\Collection {
all: [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
],
}
*/
Flip a collection of rows and values per column so its columns become rows and its rows become columns.
Before:
id | name | |
---|---|---|
A | 1 | James |
B | 2 | Joe |
C | 3 | Jonas |
After:
A | B | C | |
---|---|---|---|
id | 1 | 2 | 3 |
name | James | Joe | Jonas |
How to use:
collect([
'A' => [
'id' => 1,
'name' => 'James',
],
'B' => [
'id' => 2,
'name' => 'Joe',
],
'C' => [
'id' => 3,
'name' => 'Jonas',
],
])->transposeWithKeys();
/*
Illuminate\Support\Collection {
all: [
"id" => [
"A" => 1,
"B" => 2,
"C" => 3,
],
"name" => [
"A" => "James",
"B" => "Joe",
"C" => "Jonas",
],
],
}
*/
You can also pass some row header names if you don't want them to be automatically guessed. You'd then call the macro with transposeWithKeys(['myID', 'row2'])
and the resulting rows would be myID
and row2
instead of id
and name
respectively.
Display structured debug information on the collection using Kint. Can be called multiple times during a collection's method chain and outputs debug information at each point of use. Continues script execution afterwards.
Requires the kint-php/kint package.
collect([
'id' => 6,
'name' => 'Sebastiaan',
])
->d()
->put('role', 'author')
->d();
See the sss helper for example output.
Display structured debug information on the collection using Kint. Halts script execution afterwards, so it can only be called once during a collection's method chain.
Requires the kint-php/kint package.
collect([
'id' => 6,
'name' => 'Sebastiaan',
])
->d()
->put('role', 'author')
->ddd();
See the sss helper for example output.
The primary use of the Constants
trait is to enable you to store all constants of a specific type in a single class or value object and have it return those with a single call.
This can be useful for instance when your database uses integers to store states, but you want to use descriptive strings throughout your code. It also allows you to refactor these constants at any time without having to waste time searching your code for any raw values (and probably miss a few, introducing new bugs along the way).
<?php
use SebastiaanLuca\Helpers\Classes\Constants;
class UserStates
{
use Constants;
const REGISTERED = 'registered';
const ACTIVATED = 'activated';
const DISABLED = 'disabled';
}
UserStates::constants();
// or
(new UserStates)->constants();
/*
[
"REGISTERED" => "registered",
"ACTIVATED" => "activated",
"DISABLED" => "disabled",
]
*/
The ProvidesClassInfo
trait provides an easy-to-use getClassDirectory()
helper method that returns the directory of the current class.
<?php
namespace Kyle\Helpers;
use SebastiaanLuca\Helpers\Classes\ProvidesClassInfo;
class MyClass
{
use ProvidesClassInfo;
public function __construct()
{
var_dump($this->getClassDirectory());
}
}
// "/Users/Kyle/Projects/laravel-helpers"
A static class helper to help you figure out the visibility/accessibility of an object's methods.
<?php
class SomeClass
{
private function aPrivateMethod() : string
{
return 'private';
}
protected function aProtectedMethod() : string
{
return 'protected';
}
public function aPublicMethod() : string
{
return 'public';
}
}
MethodHelper::hasMethodOfType($class, 'aPrivateMethod', 'private');
// true
MethodHelper::hasProtectedMethod($class, 'aProtectedMethod');
// true
MethodHelper::hasPublicMethod($class, 'aPublicMethod');
// true
MethodHelper::hasProtectedMethod($class, 'aPrivateMethod');
// false
MethodHelper::hasPublicMethod($class, 'invalidMethod');
// false
The database table reader gives you detailed information about a given table, especially in the context of a Laravel Eloquent model.
Note that this has only been tested with MySQL databases, although it might work with others too as it uses a raw describe
statement to get a table's information. Uses the default database connection by default when resolved from the DI container, but you can set your own before calling read
.
Note: unless otherwise specified, call each method after reading the table to allow for it to return something.
Requires the illuminate/database package.
Create a new reader to set up its internal database manager and connection:
$reader = app(\SebastiaanLuca\Helpers\Database\TableReader::class);
Then read the table:
$reader->read('users');
Get the database connection used to read the table.
Set the database connection used to read the table. Do this before reading the table.
app(\SebastiaanLuca\Helpers\Database\TableReader::class)
->setConnection($connection)
->read('users');
Get the table name that was read.
Get all the table's fields and additional raw information as an array.
Get a simple list of all the table's column names.
Get a simple list of all the table's guarded fields.
Compares the table's columns with a default list and returns matches.
Currently supported:
id
password
password_hash
created_at
updated_at
deleted_at
Get all mass-assignable attributes.
Compares default fillable fields with the ones in the table.
Get all attributes that can be casted to native types.
Matches table column types with their native counterparts.
Currently supported:
int
tointeger
tinyint(1)
toboolean
json
toarray
Get all attributes that can be converted to Carbon DateTime instances.
Currently supported:
timestamp
datetime
date
time
year
Get all attributes that can be NULL
.
Check if the table has a given column.
Check if the table uses Eloquent timestamps (created_at
and updated_at
).
Check if the table uses Eloquent soft deletes (deleted_at
).
This package operates under the MIT License (MIT). Please see LICENSE for more information.
Please see CHANGELOG for more information what has changed recently.
composer install
composer test
Please see CONTRIBUTING and CONDUCT for details.
If you discover any security related issues, please email hello@sebastiaanluca.com instead of using the issue tracker.
My name is Sebastiaan and I'm a freelance Laravel developer specializing in building custom Laravel applications. Check out my portfolio for more information, my blog for the latest tips and tricks, and my other packages to kick-start your next project.
Have a project that could use some guidance? Send me an e-mail at hello@sebastiaanluca.com!