Lesser-Known Laravel Helper Functions Every Developer Must Know (And How to Build Your Own)

Yash Kumar Prasad
4 min readOct 22, 2024

--

Introduction

Laravel is known for its rich syntax and powerful features, one of which is an extensive collection of helper functions. This functionality makes your code cleaner, faster, and easier to maintain. While most developers are familiar with common helpers like route(), url(), and asset(), there are many lesser-known helper functions that can greatly improve your development process

In this post, we’ll cover some of these little-used helper functions that every Laravel developer should have in their toolkit. We will show you how to create your own custom helper functions to make your code more efficient and tailored to your specific needs.

1. str_slug()

This function is often overlooked, but it’s essential when you’re working with SEO-friendly URLs or slugs for your content. It converts a string into a slug format.

Example:

$slug = str_slug('Laravel 10 Helper Functions'); 
// Outputs: 'laravel-10-helper-functions'

Although str_slug() was removed in Laravel 6.x in favor of Str::slug(), you can still use it by manually importing the helper or upgrading your Laravel version.

Use case:

Creating slugs for blog posts, product titles, or user-generated content.

2. array_wrap()

This simple but useful helper ensures that a given value is always wrapped in an array. If the value is already an array, it remains unchanged.

Example:

$result = array_wrap('single-item');
// Outputs: ['single-item']

$result = array_wrap(['multi', 'item']);
// Outputs: ['multi', 'item']

Use case:

When dealing with data that might be either a single item or an array, this function ensures uniformity.

3. blank()

This helper checks if a given value is “blank” (i.e., empty, null, or zero-length string). It’s an enhancement over the usual empty() or isset() checks, and it’s far more flexible.

Example:

blank('');         // true
blank(null); // true
blank([]); // true
blank('Laravel'); // false

Use case:

Useful for checking form inputs or query parameters in a consistent manner.

4. filled()

While blank() checks if a value is empty, filled() checks if it is not. It’s the inverse of blank() and can be handy in specific scenarios.

Example:

filled('Laravel');  // true
filled(''); // false
filled(null); // false

Use case:

This function is great for validating fields that must be filled before proceeding in a form or user request.

5. retry()

This helper allows you to retry a given callback a specified number of times before throwing an exception. It’s handy for handling tasks that may fail temporarily, like network requests or database queries.

Example:

$result = retry(5, function () {
// Perform some task that may fail
return $this->api->makeRequest();
}, 100);

In this example, the callback will be attempted up to 5 times, waiting 100 milliseconds between each attempt.

Use case:

Useful for tasks like hitting external APIs, where intermittent failures might occur.

6. data_get()

data_get() allows you to easily access deeply nested data in arrays or objects using dot notation, with an optional default value if the key doesn’t exist.

Example:

$array = ['users' => ['name' => 'John']];
$name = data_get($array, 'users.name');
// Outputs: 'John'

$default = data_get($array, 'users.age', 30);
// Outputs: 30 (default value if 'age' does not exist)

Use case:

This is excellent for working with complex datasets where accessing nested elements might otherwise be cumbersome.

How to Create Your Own Helper Functions

Laravel makes it incredibly simple to create your own custom helper functions to tailor your application. Here’s a quick guide:

Step 1: Create a Helpers File

Start by creating a helpers.php file in the app/ directory (or any directory of your choice).

// File: app/helpers.php
<?php

function format_currency($amount, $currency = 'USD') {
return number_format($amount, 2) . ' ' . $currency;
}

Step 2: Autoload the File

To make sure Laravel can access these functions, you’ll need to autoload the file. Open composer.json and add your helpers.php file under the autoload section:

"autoload": {
"files": [
"app/helpers.php"
]
}

Step 3: Run Composer Dump Autoload

Once you’ve added your file to the autoload section, run the following command to reload your helpers:

composer dump-autoload

Step 4: Use Your Custom Helper

Now, you can use the format_currency() function anywhere in your application:

echo format_currency(1500); 
// Outputs: '1,500.00 USD'

Conclusion

Laravel’s helper capabilities provide a treasure trove of utilities that make your code cleanser and more green. While we regularly use the most not unusual ones, digging deeper into the lesser-regarded helpers can screen effective gear which could appreciably streamline your workflow. Additionally, building your personal custom helper capabilities permits you to tailor the framework to your unique wishes, making your improvement manner smoother.

Whether you are trying to optimize your present Laravel initiatives or personalize the framework further, these helpers and custom solutions will certainly beautify your codebase.

Do you have other favorite helper functions? Let us know in the comments below!

Call to Action

Interested in more Laravel tips and tricks? Be sure to subscribe to our blog for more tutorials and in-depth guides!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.

No responses yet

Write a response