How to create custom helper in codeigniter 4

Created at 18-May-2021 , By samar

How to create custom helper in codeigniter 4

In this session, we will try our hand at solving the "How to create custom helper in codeigniter 4".

This code snippet provides you a solution for how to create a custom helper in Codeigniter 4. For this, you have to first create a helper file and after that, you can autoload in your base controller or in your controller’s method. Now you can display it in your view file.
  • 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.