By Hamza Ali LAST UPDATED AUG 26, 2018
 12,669
104

Laravel provides us with many built-in helper functions that you can call anywhere within your application. They make you workflow convenient for working with arrays & objects, paths, strings, URLs and other types.

Although there are many helper functions defined in the laravel core, you can define your own helper functions in laravel to avoid repeating the same code. It ensures better maintainability of your application.

Let’s walk through how you can create your own custom Laravel helper functions.

Helpers in Laravel

There are many built-in helpers available in the laravel that you can use in your applications. They are grouped based on the type of functionality they provide. Here is a complete documentation of built-in laravel helpers.

Arrays & Objects

In this group, helpers provide the ability to work with arrays & objects. This group contains helper functions to add two arrays, collapse multidimensional array into a single array, return the first element of the array, check whether a given item or items exist in an array and perform many other types of manipulations.

Paths

This group of helpers returns absolute paths of different directories in your Laravel application like app, config, public, resource, storage and your application base path as well.

Strings

Helpers in this group work with string manipulation. You can convert strings to camel case, find the basename of the class, run htmlspecialchars, convert text to kebab case, convert text to snake case, and perform many other types of string manipulations.

URLs

URLs group of helpers works with generating URLs. You can generate URL for the controller action, named route, and fully qualified URL to the given path.

Miscellaneous

This category of helpers contains functions for working with page status, service container, authentication, cache etc.

Creating a Helper file in Laravel

In this section, we will go through creating a Laravel helper file that can be used globally in a Laravel application. You can organize the location of your helper file, however, I prefer to keep my Laravel project helper file in app/Helpers/Helper.php. In this tutorial, we will create a helper file in my desired location.

Creating Helpers file

You could place your helper file anywhere in your Laravel application, it is standard to put it under your appdirectory.

Let’s create a Helpers directory under app and create a Helper.php file. These are the following contents of the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
 
if (!function_exists('human_file_size')) {
    /**
     * Returns a human readable file size
     *
     * @param integer $bytes
     * Bytes contains the size of the bytes to convert
     *
     * @param integer $decimals
     * Number of decimal places to be returned
     *
     * @return string a string in human readable format
     *
     * */
    function human_file_size($bytes, $decimals = 2)
    {
        $sz = 'BKMGTPE';
        $factor = (int)floor((strlen($bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $sz[$factor];
 
    }
}
 
if (!function_exists('in_arrayi')) {
 
    /**
     * Checks if a value exists in an array in a case-insensitive manner
     *
     * @param mixed $needle
     * The searched value
     *
     * @param $haystack
     * The array
     *
     * @param bool $strict [optional]
     * If set to true type of needle will also be matched
     *
     * @return bool true if needle is found in the array,
     * false otherwise
     */
    function in_arrayi($needle, $haystack, $strict = false)
    {
        return in_array(strtolower($needle), array_map('strtolower', $haystack), $strict);
    }
}

If you are using a class and its methods are your helpers you can start the file with namespace declaration.

1
namespace App\Helpers;

If you do not use the namespace declaration, these functions will become globally available and you can use them without even specifying the namespace. All the Laravel built-in helper functions are defined without a namespace. Also, helper class will also be available globally. Therefore, if you want to use helpers without specifying namespace simply remove this line.

There are a few caveats when defining these functions. All the Laravel helper files functions are rapped in a check to avoid function definition collisions.

1
2
3
4
5
6
if (!function_exists('human_file_size')) {
    function human_file_size($bytes, $decimals = 2)
    {
        // ...
    }
}

If you skip this check, collisions will occur any time you redefine a function with the same definition. You could either use this check or you could also prefix your function names to avoid collisions.

Using the Helper file

Now, that’s it as far as our helper file is concerned. Let’s see how you can use helper file in Laravel application.

  • You can either autoload helper file with composer. Then, you could use these functions anywhere in your application.
  • You could also use the Laravel service provider to register this file. Laravel will load it along with other dependencies.
  • You can also use a package that gives you all of this functionality.

Let’s see how we can use all of these methods.

Using Composer to Autoload Files

First one is pretty easy and straightforward. Simply go to composer.json file located in your Laravel project and you will see autoload key. Composer has a files key (an array of file paths that you want to autoload) that you can use in your autoload key. It will look like this:

1
2
3
4
5
6
7
8
9
10
11
12
"autoload": {
    "files": [
        "app/Helpers/Helper.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

After changing composer.json file and adding a new path to the files array, you need to dump the autoloader. Simply run this command from the terminal in your Laravel project directory.

1
composer dump-autoload

Now your helper file will be automatically loaded in your Laravel project.

Using service providers to load file

Let’s see how you can use service providers to autoload Helper file. Go to the command line in the root of your application and run the following command to create a new service provider.

1
php artisan make:provider HelperServiceProvider

You will see this message logged onto your console screen

Provider created successfully.

Once the service provider is created successfully, open that file. In the register method require your Helper files.

1
2
3
4
5
6
7
public function register()
{
    $file = app_path('Helpers/Helper.php');
    if (file_exists($file)) {
        require_once($file);
    }
}

In the register method, we include our dependencies. In a large-scale project, it is possible that you have multiple helper files in a directory and you want to require all of them. You could change the register method like given below and your service provider will load all of the files in the Helpers directory.

1
2
3
4
5
6
public function register()
{
    foreach (glob(app_path() . '/Helpers/*.php') as $file) {
        require_once($file);
    }
}

It will require all of the files present in the app/Helpers directory.
Now that our service provider is completed, we need to register our service provider, so, that Laravel will load it during bootstrapping. For this, go to config/app.php and add the following line in the providers array at the end.

1
App\Providers\HelperServiceProvider::class,

If your helper file involves a class that has those helper methods and you have specified namespace, you could use them with little effort by defining an alias. You can do that easily by adding the following at the end of the aliases array in config/app.php file.

1
'Helper' => App\Helpers\Helper::class,

By adding this in the alias array, you will be able to call your helpers by using the Helper keyword. That’s all for creating your helpers with service providers.

Using a third party package

You could also use a third party package. Github page for the Laravel helpers package. You could install it via composer by running this command from the root of your application in console.

composer require browner12/helpers

Add the following line in the providers array in config/app.php

browner12\helpers\HelperServiceProvider::class,

If you are using Laravel’s automatic package discovery, you can skip this step.
After completing the necessary steps, you could use this command to create a Helper file.

php artisan make:helper Helper

It will create a Helper.php file in App\Helpers where you could easily add all of your helper functions.

Helper in Action

Now that we have our functions defined in our Helper file without a namespace defined, we could use them very easily. Simply go to your routes file at routes/web.php and use this function for the home page route. For instance, this is the complete routes/web.php file without comments:

1
2
3
4
5
<?php
 
Route::get('/', function () {
    return human_file_size(1024*1024);
});

It will simply return a human-readable size of the number of bytes passed as the parameter. You could call these functions from anywhere controllers or views.

Recommended Learning:


Resources

Check out all of the built-in Laravel helpers available.
A simple package to create helper file browner12/helpers.
Learn more about using Composer Autoloader

Leave your comments, problems or queries in the feed below. I will respond to them as fast as I can.

Creating Your Own PHP Helper Functions In Laravel的更多相关文章

  1. libevent reference Mannual IV --Helper functions and types

    FYI: http://www.wangafu.net/~nickm/libevent-book/Ref5_evutil.html Helper functions and types for Lib ...

  2. asp.net MVC 帮助助手和函数( @helper @functions)

    asp.net Razor 视图具有.cshtml后缀,可以轻松的实现c#代码和html标签的切换,大大提升了我们的开发效率.但是Razor语法还是有一些棉花糖值得我们了解一下,可以更加强劲的提升我们 ...

  3. libevent学习五(Helper functions and types for Libevent)

    基础类型   #ifdef WIN32 #define evutil_socket_t intptr_t #else #define evutil_socket_t int #endif ev_ssi ...

  4. Laravel 5.2+ 使用url()全局函数返回前一个页面的地址

    注意:文章标题中5.2+表示该文章内容可向上兼容,适用于Laravel版本5.2及更高(目前最新为5.6),但不可向下兼容,即不适用于5.2版本以下.推荐大家花一点点时间,将自己的Laravel更新至 ...

  5. C-Language Functions

    转自:https://www.postgresql.org/docs/9.6/xfunc-c.html 可以作为学习基于c编写pg extension 的资料 36.9. C-Language Fun ...

  6. 转: Laravel 自定义公共函数的引入

    来源:Laravel 自定义公共函数的引入 背景习惯了 使用 ThinkPHP 框架,有一个公共方法类在代码编写上会快捷很多,所以有必要在此进行配置一番.测试框架:Laravel 5.5步骤指导1. ...

  7. How to use external classes and PHP files in Laravel Controller?

    By: Povilas Korop Laravel is an MVC framework with its own folder structure, but sometimes we want t ...

  8. Laravel Debugbar

    Installation Require this package with composer: composer require barryvdh/laravel-debugbar After up ...

  9. laravel自定义公共函数的引入

    原文地址:http://blog.csdn.net/u011415782/article/details/78925048 步骤指导 1. 创建 functions.php 在 app/Helpers ...

随机推荐

  1. Genomic signatures of evolutionary transitions from solitary to group living(独居到社会性的转变)

    1.摘要 群居性的进化是进化的主要过渡之一,但其背后的基因组变化是未知的.我们比较了10种蜜蜂的基因组,它们的社会复杂性各不相同,代表了社会进化中的多种独立过渡,并报告了三项主要发现. 第一,许多重要 ...

  2. 开启Centos系统的SSH服务

    1.登录Centos6.4系统. ◆示例:使用root用户登录. 注:若为非root用户登录,输入执行某些命权限不够时需加sudo. 查看SSH是否安装. 2.◆输入命令:rpm -qa | grep ...

  3. app.use

    [app.use] app.use([path,] function [, function...]) Mounting a middleware at a path will cause the m ...

  4. 使用rsync 同步数据一些常用参数和示例

    rsync rsync是linux系统下的数据镜像备份工具.支持远程同步,本地复制,或者与其他SSH.rsync主机同步. 包括本地推到远程,远程拉到本地两种同步方式,也可以实现本地不同路径下文件的同 ...

  5. python 常用模块(一): random , time , sys , os模块部分知识.

    1.常用模块:(1)collectiaons模块 (2)与时间相关  time模块 (3)random模块 (4)os模块 (5)sys模块 (6) 序列化模块: json  ,   pickle 2 ...

  6. 【Spider】使用命令行启动时,能正常抓取,但是在pycharm直接运行不能保存数据

    通过cmd 运行命令scrapy crawl [爬虫名称]可以正常运行,并把数据保存到json文件和下载爬取的图片 但是在项目的spiders目录下的 firstTestSpider.py文件里添加: ...

  7. rancher 2 webhook 格式

    { "version":"4", "groupKey":<string>, "status":"& ...

  8. poj3292(筛法+打表)

    题目链接:https://vjudge.net/problem/POJ-3292 题意:定义4n+1数(简称H数),H数分为三类:unit,即为1; H-primes,只能分解为1×自身,类似于我们平 ...

  9. poj3104(二分)

    题目链接:http://poj.org/problem?id=3104 题意:有n件衣服,每一件含有a[i]单位的水,每分钟衣服可以自然蒸发1单位的水,也可以在烘干器上每分钟烘干k单位的水,问将所有衣 ...

  10. Linux之须知

    1.服务器有哪些硬件? 主板,cpu,显卡,内存,硬盘,声卡,网卡 2.内存,CPU,硬盘的作用? cpu是管理与运算.内存:cpu和磁盘之间的缓冲设备,服务器关闭后,数据从内存中释放掉. CPU,电 ...