How to call helper function in Codeigniter view

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.

Answers 3
  • 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)); 
        }
    }
    
    0
  • 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");
    
    0

    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');  ?>
    
    0

    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