Laravel custom helper functions – Fast Tips
Helper functions are quite popular among Laravel developers. They provide access to some clever algorithms ready to be used in your code using a single statement.
Probably the most known helper function is url() that allows you to generate internal application URLs.
Another great helper is the retry() function for example: https://laravel.com/docs/11.x/helpers#method-retry
Easy way to retry a statement a certain number of times if it fires an exception. It’s usually used on external API calls, and in fact it was recently integrated as a method in the Laravel HTTP client.
$response = Http::retry(3, 100)->post(/* ... */);
More about HTTP client on the dedicated article: https://inspector.dev/laravel-http-client-overview-and-monitoring/
Laravel helper functions use case
Sometimes we would like to automate tasks related to our business logic and encapsulating it into an helper function could be very convenient. I wrote about the implementation of array_map for associative arrays that is a perfect fit for this use case.
You can refer to the article to know the purpose of this function, in this context I want to make it a custom helper function to be used inside your Laravel application.
How to register new Laravel helper functions
First create a new file helper.php in the app/ directory of your Laravel project.
Paste the code below to declare the array_map_assoc function into the file:
if (!function_exists('array_map_assoc')) { /** * Apply a mapping callback receiving key and value as arguments. * The standard array_map doesn't pass the key to the callback. But in the case of associative arrays, * it could be really helpful. * * array_map_assoc(function ($key, $value) { * ... * }, $items) * * @param callable $callback * @param array $array * @return array */ function array_map_assoc(callable $callback, array $array): array { // map original array keys, and call $callable with $key and $value. return array_map(function($key) use ($callback, $array){ return $callback($key, $array[$key]); }, array_keys($array)); } }
As you can see the function declaration is wrapped by the if to avoid registering functions with the same name.
Include the helper file via Composer's autoload
Laravel doesn't automatically load custom helper files, so you need to manually instruct composer to include the file during the autoload generation.
In the composer.json file of your Laravel project find the "autoload" section, and add the “files” keyword:
"autoload": { "psr-4": { "App\": "app/", "Database\Factories\": "database/factories/", "Database\Seeders\": "database/seeders/" }, "files": [ "app/helpers.php" ] },
After adding the file, run composer dump-autoload in your terminal to refresh Composer’s autoload files.
Using Your Laravel Helper Function
Once the helper file is loaded, you can use your custom functions anywhere in your Laravel application just like any other PHP function.
$histogram = array_map_assoc(function ($key, $value) { return [ 'label' => $key, 'value' => $value['doc_count'] ]; }, $data);
Hope it's helpful to stay organized with your codebase.
For more technical articles you can follow me on Linkedin or X.
Monitor your PHP application for free
Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don't need to install anything at the server level, just install the Laravel or Symfony package and you are ready to go.
If you are looking for HTTP monitoring, database query insights, and the ability to forward alerts and notifications into your preferred messaging environment, try Inspector for free. Register your account.
Or learn more on the website: https://inspector.dev
The above is the detailed content of Laravel custom helper functions – Fast Tips. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
