Laravel, PHP

How to create a globally accessible helper class in Laravel 5.5

ee75bc23653e93eb458b0e09466fed17
14 / 100

Helper class in laravel is a class that contains all those functions which are performs common tasks and can be reused in our application. Here we will create a class which contains reusable functions and these functions can be called every where in your laravel application. So let’s start to create our helper class that will globally accessible.

How to create helper class in laravel

  1. Create a folder inside app directory where your class file will locate. I create helper
  2. Create a php file. I create Helper.php
  3. Now declare your class and functions inside the Helper.php file
<?php

class Helper{

//Return specific data of any column of a table

public static function name($id,$model,$ret){
$get=$model::where('id','=',$id)->get();
 foreach ($get as $key => $gets) {
    return $gets->$ret;
 }
}

// Get all data in array form of a table by passing model name

public static function getAll($model){

    $get=$model::all();
        return $get;
}

public static function getSpecific($model,$col,$condition){

$get=$model::where($col,"like",'%'.$condition.'%')->get();
return $get;    
}

public static function getColumn($model,$col,$condition,$operator,$ret){
    if($operator=='like'){
     $condition='%'.$condition.'%';
    }
$get=$model::where($col,$operator,$condition)->get();
foreach ($get as $key => $value) {
    return $value->$ret;
}
    
}
}

?>
  1. Open your composer.json file and write your file location here

Helper class in laravel

"files": [

"app/Helper/Helper.php",
]
  1. Run composer dump-autoload command
composer dump-autoload command
  1. And now finally your class is ready to access into overall laravel application. Trying to access a static function of Helper class named ‘name($id,$model,$ret)’. This function takes 3 parameters

Laravel 5.6 is going to release .check new features.

  • $id – id of the row
  • $model – Name of model where we will search record.
  • $ret – Name of returning column after matching record successfully in the table. like email,name etc.
Helper::name($id,'App\User','name');

Explore More

If you interested to learn more about the helpers claas in laravel , you can visit the official website of laravelĀ https://laravel.com/docs/5.5/helpers.
You can also read a detailed article https://laravel-news.com/creating-helpers

Hope guys it will help you to create a custom globally accessible helper class in laravel. If you like this post please like and share it. And keep visiting our blog for more latest posts.

Thank you

Please follow and like us:

About Viren-Dra Yadav

Tech Enthusiast | Open Source Lover | WordPress Explorer | Mad for Speed | DevOps Engineer | AgriTech
View all posts by Viren-Dra Yadav →

Leave a Reply

Your email address will not be published. Required fields are marked *