How to Create Global Function in Laravel that can be access from Anywhere

Sometimes You may reach in the satuation where you need to create Common function that can be access from any View.Like you need to create a Common/Global layout function for posts that can called from any view where Posts list need to show.

Steps for creating Common function in Laravel!

  1. Create a folder named `Helpers` in Laravel app directory if not exists in app directory.
  2. Create a php file named `functions.php` (You can put any name as you want).
  3. Typical functions.php file code like below.Please replace functions name and code in `functions.php` file according to your needs.In functions.php file you can define as many functions you want.
    
    
    if (!function_exists('sluggify')) {
    	
    	
    function sluggify($url)
    {
        # Prep string with some basic normalization
        $url = strtolower($url);
        $url = strip_tags($url);
        $url = stripslashes($url);
        $url = html_entity_decode($url);
    
        # Remove quotes (can't, etc.)
        $url = str_replace('\'', '', $url);
    
        # Replace non-alpha numeric with hyphens
        $match = '/[^a-z0-9]+/';
        $replace = '-';
        $url = preg_replace($match, $replace, $url);
    
        $url = trim($url, '-');
    
        return $url;
    }
    	
  4. Create a file named `HelperServiceProvider.php` in app\Providers directory. HelperServiceProvider.php will
    
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    
    class HelperServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap the application services.
         *
         * @return void
         */
        public function boot()
        {
            //
        }
    
        /**
         * Register the application services.
         *
         * @return void
         */
        public function register()
        {
         foreach (glob(app_path() . '/Helpers/*.php') as $file) {
            require_once($file);
        }
        }
    }
    
  5. In last step Go to config/app.php and add this code in providers array.
    App\Providers\HelperServiceProvider::class,

Now you will be able to call above function directly from any views like below example.


0 comments

There is no comments added for this topic
Post comment Comments (0)