40 Lesser-Known Laravel Helper Functions Every Laravel Developer Must Know, Plus How to Build Your Own
While Laravel’s well-known helper functions are widely used, there are many lesser-known ones that can significantly enhance your development workflow.
I love how these helper functions can come in very handy and can be called in any part of your laravel codebase. These can help streamline tasks, improve code readability, and boost productivity. Here are 40 rare yet valuable Laravel helper functions:
Let’s start with the normal and then move into the best. You are going to see many beautiful functions that will really boost your application speed and efficiency. Let’s go.
1. filled()
The filled
function checks if a value is not empty, which can be more intuitive than using !empty()
.
$value = 'some text';
if (filled($value)) {
echo 'Value is not empty'; // This will be output
} else {
echo 'Value is empty';
}
2. blank()
The blank
function checks if a value is empty. This is useful for the opposite case of filled()
.
$value1 = '';
$value2 = null;
$value3 = 'Laravel';
if (blank($value1)) {
echo 'Value 1 is blank'; // Outputs this
}
if (blank($value2)) {
echo 'Value 2 is blank'; // Outputs this
}
if (blank($value3)) {
echo 'Value 3 is blank'; // Does not output this
}
3. retry()
The retry
function retries an operation a given number of times with a specified delay between attempts. This is useful for operations that might fail intermittently, such as network requests or database transactions.
See how retry
can handle transient failures by retrying the operation up to 5 times with a 100-millisecond delay between attempts.
$result = retry(5, function () {
// Simulate a risky operation that might fail
if (rand(0, 1)) {
throw new Exception('Failed');
}
return 'Success';
}, 100);
echo $result; // Outputs: 'Success' if the operation eventually succeeds
4. throw_if()
The throw_if
function throws an exception if a given condition is true. This can make your code cleaner by reducing nested if statements.
$user = null;
throw_if(!$user, Exception::class, 'User not found');
// This will throw an exception with the message 'User not found'
5. throw_unless()
The throw_unless
function throws an exception unless a given condition is true. It's the inverse of throw_if
. This function is useful when you want to ensure a condition is met and otherwise handle the error.
$user = User::find(1);
throw_unless($user, Exception::class, 'User not found');
// This will throw an exception if $user is null
6. transform()
The transform
function conditionally transforms a value using a given callback. This is useful for modifying values in a clean and readable way. Here an example where the input string is transformed to uppercase if it is not null. If the input were null, the default value would be returned.
$input = 'hello world';
$output = transform($input, function ($value) {
return strtoupper($value);
}, 'default value');
echo $output; // Outputs: HELLO WORLD
7. optional()
The optional
function allows you to access properties or call methods on an object that may be null without triggering an error. This is useful for avoiding null checks.
$user = null;
$name = optional($user)->name;
echo $name; // Outputs: nothing (null) without causing an error
8. cache()
The cache
function retrieves or stores items in the cache. This is useful for optimizing performance by caching expensive operations. You can set the time the cache would last.
It can save time and resources by the way of making you avoid repetitive calls t the database.
$value = cache('key', function () {
return DB::table('users')->get();
}, 60);
echo $value; // Outputs cached user data
9.logger()
The logger
function logs a message to the log file. This is useful for debugging and monitoring which can help track the flow of your application and diagnose issues.
logger('This is a debug message.');
10. cookie()
The cookie
function creates a new cookie instance. This is useful for setting cookies in your application.
$cookie = cookie('name', 'value', 60);
return response('Hello')->cookie($cookie);
11. csrf_field()
The csrf_field
function generates a hidden input field containing the CSRF token. This is essential for protecting forms against cross-site request forgery.
<form method="POST" action="/submit">
{{ csrf_field() }}
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
@csrf
can be used instead in blade files. They both do the same thing.
12. csrf_token()
The csrf_token
function retrieves the current CSRF token. This is useful for including the token in API requests or custom forms.
$token = csrf_token();
echo $token; // Outputs the current CSRF token
13. encrypt() and decrypt()
The encrypt
function encrypts a given value. This is useful for securing sensitive information before storing it.
The decrypt
function decrypts a given value. This is useful for handling encrypted data stored in the database or received from the user.
$encryptedValue = encrypt('mySecret');
$decryptedValue = decrypt($encryptedValue);
echo $decryptedValue; // Outputs: mySecret
14. e()
The e
function escapes HTML entities in a string. This is useful for preventing XSS attacks by escaping user input. You should know that escaping HTML entities ensures that user input is safely displayed in the browser.
$userInput = '<script>alert("Hello")</script>';
echo e($userInput); // Outputs: <script>alert("Hello")</script>
15. rescue()
The rescue
function executes a callback and returns a default value if an exception occurs. This is useful for handling exceptions in a controlled way.
$value = rescue(function () {
return riskyOperation();
}, 'default');
echo $value; // Outputs: 'default' if an exception occurs
16. broadcast()
The broadcast
function broadcasts an event. This is useful for real-time notifications and updates in your application.
broadcast(new UserRegistered($user));
17. bcrypt()
The bcrypt
function hashes a value using Bcrypt. This is essential for securely storing passwords.
$hashedPassword = bcrypt('password');
echo $hashedPassword; // Outputs a hashed password string
18. data_fill()
I love this one. The data_fill
function fills in missing data in an array or object using "dot" notation. This is useful for setting default values.
$data = ['product' => ['name' => 'Desk']];
data_fill($data, 'product.price', 100);
print_r($data); // Outputs: ['product' => ['name' => 'Desk', 'price' => 100]]
19. data_get()
The data_get
function retrieves a value from a nested array or object using "dot" notation. This is useful for accessing deeply nested data structures.
$data = ['product' => ['name' => 'Desk', 'price' => 100]];
$name = data_get($data, 'product.name');
echo $name; // Outputs: Desk
Do you know you can easily create your own helper functions? Yes, you can. I wrote a step by step article on it here
20. data_set()
The data_set
function sets a value within a deeply nested array or object using "dot" notation. This is useful for updating specific parts of complex data structures.
$data = ['product' => ['name' => 'Desk']];
data_set($data, 'product.price', 200);
print_r($data); // Outputs: ['product' => ['name' => 'Desk', 'price' => 200]]
21. report()
The report
function reports an exception. This is useful for logging exceptions to your error tracking service.
try {
// Some code that may throw an exception
} catch (Exception $e) {
report($e);
}
22. resolve()
The resolve
function resolves a service from the Laravel service container. This is useful for accessing services without needing to manually inject them.
$service = resolve('App\Services\MyService');
$service->performTask();
23. session
This one is not so rare. The session
function gets or sets session values. This is useful for managing user sessions in your application.
session(['key' => 'value']);
$value = session('key');
echo $value; // Outputs: value
24. validator()
The validator
function creates a new validator instance. This is useful for validating data against defined rules.
$validator = validator(['name' => 'John'], ['name' => 'required|string|max:255']);
if ($validator->fails()) {
// Handle validation failure
echo 'Validation failed';
} else {
// Handle validation success
echo 'Validation succeeded';
}
25. value()
The value
function returns the value it is given. If a Closure is given, it will be executed and its result returned. This is useful for conditionally setting values.
$value = value(function () {
return 'result';
});
echo $value; // Outputs: result
26. windows_os()
The windows_os
function checks if the application is running on Windows. This is useful for handling platform-specific behavior.
if (windows_os()) {
echo 'Running on Windows';
} else {
echo 'Not running on Windows';
}
27. method_field()
The method_field
function generates a hidden input field containing the spoofed HTTP verb. This is essential for forms that need to submit a method other than GET or POST.
<form method="POST" action="/update">
{{ method_field('PUT') }}
{{ csrf_field() }}
<input type="text" name="name">
<button type="submit">Update</button>
</form>
28. trans()
The trans
function translates the given message. This is useful for localizing your application.
echo trans('messages.welcome'); // Outputs: 'Welcome' or a translated message
29. trans_choice()
The trans_choice
function translates the given message based on a count. This is useful for handling pluralization.
echo trans_choice('messages.apples', 10); // Outputs: '10 apples' or a translated message
30. __()
The __
function gets the translation for the given key. This is a shorthand for trans()
.
echo __('messages.welcome'); // Outputs: 'Welcome' or a translated message
Do you know you can easily create your own helper functions? Yes, you can. I wrote a step by step article on it here
31. class_uses_recursive()
The class_uses_recursive
function returns all traits used by a class, including those used by its parent classes. This is useful for introspection and debugging and helps you understand the composition of a class, especially in complex inheritance hierarchies.
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
use Str;
}
$traits = class_uses_recursive(User::class);
print_r($traits); // Outputs: array of traits used by User and its parent classes
32. collect()
The collect
function creates a new collection instance from the given value. This is useful for working with arrays and data structures in a more fluent and expressive way.
$collection = collect([1, 2, 3, 4, 5])
->map(function ($item) {
return $item * 2;
})
->reject(function ($item) {
return $item < 8;
});
print_r($collection->all()); // Outputs: [8, 10]
33. dispatch()
The dispatch
function dispatches a job to its appropriate handler. This is useful for queuing jobs in a clean and readable manner.
dispatch(new App\Jobs\SendEmailJob($user));
34. head()
The head
function returns the first element of an array. This is useful for quickly accessing the first item without needing to reset array keys.
$array = [100, 200, 300];
$firstElement = head($array);
echo $firstElement; // Outputs: 100
35. last()
The last
function returns the last element of an array. This is useful for quickly accessing the last item without needing to reset array keys.
$array = [100, 200, 300];
$lastElement = last($array);
echo $lastElement; // Outputs: 300
36. policy()
The policy
function retrieves a policy instance for a given class. This is useful for checking authorization rules.
$policy = policy(App\Models\Post::class);
if ($policy->update($user, $post)) {
echo 'User can update the post';
} else {
echo 'User cannot update the post';
}
37. with()
The with
function returns the given value. This is useful for chaining methods or assigning a value to a variable within a chain. It makes your code more readable.
$value = with('some value', function ($value) {
return strtoupper($value);
});
echo $value; // Outputs: SOME VALUE
38. preg_replace_array()
The preg_replace_array
function performs a regular expression search and replace on a subject, using an array of replacements. This is useful for performing multiple replacements in a string based on regular expressions.
$pattern = '/(Laravel|PHP)/';
$replacements = ['Lumen', 'JavaScript'];
$text = 'Laravel is a PHP framework. Laravel is great.';
$replaced = preg_replace_array($pattern, $replacements, $text);
echo $replaced; // Outputs: 'Lumen is a JavaScript framework. Laravel is great.'
39. today() and now()
The today
function returns the current date at midnight. This is useful for generating date values that are standardized to the start of the day.
The now
function returns a Carbon instance for the current date and time. This is useful for working with date and time values in a standardized and powerful way using the Carbon library, which provides extensive functionality for date manipulation and formatting.
$today = today();
echo $today; // Outputs: current date at 00:00:00
$now = now();
echo $now; // Outputs: current date and time in the default format
// Formatting the date
$formattedNow = now()->format('Y-m-d H:i:s');
echo $formattedNow; // Outputs: current date and time in 'YYYY-MM-DD HH:MM:SS' format
// Adding time
$future = now()->addDays(5);
echo $future; // Outputs: date and time five days from now
// Subtracting time
$past = now()->subHours(3);
echo $past; // Outputs: date and time three hours ago
40. type_of()
The type_of
function returns the type of the given value. This is useful for debugging and ensuring that values are of the expected type.
$type = type_of(123);
echo $type; // Outputs: integer
$type = type_of('Laravel');
echo $type; // Outputs: string
Conclusion
The reason I love these functions is that you can call them in any part of your laravel code without any imports or resolve. They are super easy to use and helps you keep the code clean and readable. You can also create custom helper functions that you can call and use anywhere in your entire codebase.
Enjoy!
Do you know you can easily create your own helper functions? Yes, you can. I wrote a step by step article on it here
Stay tuned!!! I will be back with some more cool Laravel tutorials in the next article. I hope you liked the article. Don’t forget to follow me 😇 and give some clap 👏. And if you have any questions feel free to comment.
Thank you.
Thanks a lot for reading till end. Follow or contact me via:
Twitter: https://twitter.com/EjimaduPrevail
Email: prevailexcellent@gmail.com
Github: https://github.com/PrevailExcel
LinkedIn: https://www.linkedin.com/in/chimeremeze-prevail-ejimadu-3a3535219
BuyMeCoffee: https://www.buymeacoffee.com/prevail
Chimeremeze Prevail Ejimadu