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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With