How to make a custom helper function, available in every controller for Laravel 5

Viewed 5870

I just read this post to make a global function which is able to be accessed from any controller. But I don't understand how it works.

I want to make variable 'services' accessible from any controller. So, I make General.php and put it in app/Http. Here is the code.

<?php
class General {

   public function getServices() {
      $services = "SELECT * FROM products";
      return $services;
   }
}

And in the controller I include it

<?php
namespace App\Http\Controllers;

use App\Http\General;
use Illuminate\Http\Request;

class HomeController extends Controller {
   public function index() {

       $title = 'Our services';
       $services = General::getServices();

       return view('welcome',  compact('title','services'));

   }
}

When I run it I got error Class 'App\Http\General' not found. And then how I can Anyone can help would be appreciated.

4 Answers

I had a problem when I was trying to register my helpers.php file within the composer.json. I had always getting function not defined error due to the fact that I included a namespace at the top of the file, but when removed it everything worked like a charm for me. So what to follow is the following:

  1. create your helpers.php file and place it in the app or bootstrap directory.

  2. make sure not to include namespace if you just want to use your functions.

  3. include in your composer.json app/helpers.php or bootstrap/helpers.php, depending where you put the file.

  4. run the command composer dump-autoload

  5. Now your functions will be accessed globally everywhere in your app.

Related