Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel-5

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.

like image 629
Abaij Avatar asked Dec 13 '22 22:12

Abaij


1 Answers

First create the required function inside the app directory within a .php file as

helpers.php

if (!function_exists('getServices')) {
    public function getServices() {
        return DB::table('services')->get();
    }
}

and include this file in composer.json inside autoload/files array as

composer.json

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php"
    ]
},

Then update the composer, now you can able to directly use the created function inside your whole project as the file is automatically loaded when application get bootstraped

$result = getServices();
like image 81
RAUSHAN KUMAR Avatar answered May 09 '23 12:05

RAUSHAN KUMAR