How to call helper function in Codeigniter view

Created at 18-May-2021 , By samar

How to call helper function in Codeigniter view

Hello everyone, in this post we will examine how to solve the "How to call helper function in Codeigniter view" programming puzzle.

You can call the helper function in Codeigniter using the function name in the view file. To call a helper method you have to first create a helper method in the helper file, autoload it in the base controller or controller’s method after that you can access it in your controller and view files.
  • Create a helper file in codeigniter 4

    --PATH app\Helpers\custom_helper.php
    <?php 
    
    if(!function_exists('changedateFormat')){
        function changedateFormat($format = 'd-m-Y', $originalDate){
            return date($format, strtotime($originalDate)); 
        }
    }
    
  • Loading helper in codeigniter 4

    Loading helper using BaseController

    app\Controllers\BaseController.php

    class BaseController extends Controller
    {
    	/**
    	 * An array of helpers to be loaded automatically upon
    	 * class instantiation. These helpers will be available
    	 * to all other controllers that extend BaseController.
    	 *
    	 * @var array
    	 */
    	protected $helpers = ['custom'];
    

    ANOTHER METHOD

    Loading helper using controller's method

    You can also load the helper in the controller's method in Codeigniter 4.

    app\Controllers\<Home>.php

    public function index(){
        
        helper("custom");
    

    There are two different methods used to load a helper in Codeigniter 4. The first is used to load the helper globally using BaseController.php and the second method is used to load the helper in the controller's method.

    The helpers property with helper name (custom in our case) will be available to all other controllers that extend BaseController.

  • Call helper method in view in Codeigniter 4

    --PATH app\Views\home.php
    <?= changedateFormat('Y-m-d', '11/05/2021');  ?>
    

    You can simply call the helper file’s methods by the function name and passing the value to it.

Back to code snippet queries related codeIgniter

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.