The Easiest Way to Create Custom Helpers in Laravel


Sometimes during programming, we are stuck with a scenario where we really want to call a controller function directly from view but failed due to the limitation of MVC. The solution is creating a custom helper functions that can be accessed from anywhere. The Laravel custom helper function will help us to avoid repetition of codes in some views. It also helps us to implement DRY (Don't Repeat Yourself) principals of software developments.

Now before we start looking at the actual implementation details I like to share you a real life scenario I faced during development of Shareurcodes. To increase the look of the website I just want to show image thumbnails of each post in my view page etc. So I created a function which accepts the body of the post and returns URL of the first image from of that post. I used the same function in my all post listing pages so one temporary option for me is to include that function in every view pages I used that function but it is a really bad practice because it is against DRY principles and another problem that will face in future is if I need change a single line of code I need to update my code in every view pages I used that function. So the solution is to create a custom helper function which can be called from anywhere ie in any view or model or controller in my Laravel Project.

laravel custom helpers - shareurcodes

So Let's start coding

STEP 1 

create a folder named Helpers inside your app folder and then create a Helper.php file inside Helpers folder. The code inside Helpers.php file is given below.

<?php

namespace App\Helpers;

class Helper {
    
    public static function your_function_name() 
    {
        // codes for your function
    }
}

STEP 2

Inorder to access your custom function from anywhere in Laravel we need to autoload it and the easiest way to autoload it by creating a aliases inside config/app.php file. The array of class aliases will be registered when this application is started but the aliases are "lazy" loaded so they don't hinder performance so you can create as many as you wanted without hindering the performance of your application. The code inside aliases array is given below.

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

STEP 3

Now you can call your custom helper function anywhere in your application as below.

Helper::your_function_name()

 

A REAL LIFE EXAMPLE

Now I will share you guys the complete code I used in shareurcodes to create thumbnail images. The function will accept post body as the parameter and will return first image URL. The code for that function is given below. 

public static function catch_first_image($post) 
    {
        $first_img = '';

        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post, $matches);

        if(!empty($matches[1][0]))
        $first_img = $matches [1] [0];

        if(empty($first_img)){ //Defines a default image

            $first_img = "/images/noimg.jpg";

        }

        return $first_img;
    }

Now in order to reuse above function in every view, I cut and paste this function to Helpers/Helper.php file. The complete code for Helper.php file is given below.

<?php

namespace App\Helpers;

class Helper {
    
    public static function catch_first_image($post) 
    {
        $first_img = '';

        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post, $matches);

        if(!empty($matches[1][0]))
        $first_img = $matches [1] [0];

        if(empty($first_img)){ //Defines a default image

            $first_img = "/images/noimg.jpg";

        }

        return $first_img;
    }
}

Now I create an alias as step 2. After creating alias now I call the above function in my views as below.

src="{{ Helper::catch_first_image($post->body) }}"

 

If you have any suggestions or doubts please comment below and I try will response to every one of you as early as possible.


Similar Posts

Web development
9th Apr 2017 09:11:57 PM
PHP Laravel
8644

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.