Call to undefined function App\Http\Controllers\get_option() in laravel 8 - php

I'm trying to convert an Laravel 5.7 project to 8, still debugging but I can't fix that spesific issue.
When I run that project I get "Call to undefined function App\Http\Controllers\get_option()" error.
I tried:
Change helpers.php location Providers to Controllers
Remove if clause in helpers.php file
Add "use App\Providers\helpers;" in Mainpage controller
Check Laravel 8 upgrading guide (https://laravel.com/docs/8.x/upgrade)
This is a source of error in App\Http\Controllers\MainpageController:
...
$products_recommendations = Product::select('product.*')
->join('product_details', 'product_details.product_id', 'product.id')
->where('product_details.show_recommendations', 1)
->orderBy('update_date', 'desc')
->take(get_option('mainpage_list_product_count'))->get();
...
This is app/Providers/helpers.php file, it has get_option() function:
<?php
use App\Models\Option;
use Illuminate\Support\Facades\Cache;
if (! function_exists('get_option')) {
function get_option($key) {
//$allOptions = Cache::rememberForever('allOptions', function() {
$minute = 60;
$allOptions = Cache::remember('allOptions', $minute, function() {
return Option::all();
});
return $allOptions->where('key', $key)->first()->variable;
}
}
How can I fix that?
Note: I translated variable and function names into English for asking here.

I added my helper again to my composer.json file:
"autoload": {
"files": [
"app/helpers.php"
],
and enter composer dump-autoload. It worked.
That solution hadn't worked before, I had to delete and rewrite it in the composer.json file.
There is another error, but at least I fixed this.

Related

composer autoload not work with global funtion [duplicate]

I am trying to make my own mock MVC framework as a project. This is my first time using composer outside of using it for requiring dependencies for Laravel. The actual autoloading works well, but when I try to autoload the helpers.php something weird happens. The file is autoloaded(if I change the path of the file I get the file not found error) but the contents inside it are not. In another file I try to call any function from the helpers.php file and I get
Fatal error: Uncaught Error: Call to undefined function
This is the file structure of the example
composer.json
App
Utils
helpers.php
public
index.php
This is my composer.json file:
{
"name": "admin/projecttest",
"autoload": {
"psr-4": {
"Admin\\Projecttest\\": "src/",
"App\\": "App/"
},
"files": [
"App/Utils/helpers.php"
]
},
"minimum-stability": "dev"
}
The helpers.php
<?php
namespace App\Utils;
use Leonlav77\Frejmcore\helpers\DotEnv;
function config($config){
$config = explode(".", $config);
$file = $config[0];
$configFile = require "../config/$file.php";
return $configFile[$config[1]];
}
function env($key, $default = null){
(new DotEnv(__DIR__ . '../../.env'))->load();
return getenv($key) ? getenv($key) : $default;
}
function baseDir(){
return __DIR__ . "/../";
}
index.php (where I call the function from the helper)
<?php
require "../vendor/autoload.php";
var_dump(function_exists('baseDir'));
var_dump(baseDir());
from the function_exists I get false
As the user Foobar suggested the the problem was in the namespace of the helpers.php . Since it had a namespace the functions also had a namespace, so insted of baseDir() I needed to use App/Utils/baseDir().
The solution was to simply remove the namespace from helpers.php

Controller not found in slim 3

I am new to slim,so please bear with me.
I have project structure like
\slim
  \public
    index.php
    
  \src
    \controllers
\reports
       BillingReportController.php
\routes
router.php
\config
db.php
But whenever I call the controller via route it gives me below error
"PHP Fatal error: Class 'src\controllers\reports\BillingReportController' not found in /var/www/html/apimod/public/index.php on line 13"
As for the line mentioned in error the snippet is as follows.
index.php
$container = $app->getContainer();
$container['BillingReportController'] = function($container){
return new \src\controllers\reports\BillingReportController;
};
router.php
$app->group('/report', function() use ($app) {
$app->get('/billing', 'BillingReportController:billing');
});
BillingReportController.php
namespace src\controllers\BillingReportController;
class BillingReportController{
public function billing($request, $response){
//my code goes here
}
}
Can anyone please point out the error.
You must've to use autoloading in your composer. something like this.
"autoload": {
"psr-4": {
"src\\": "src"
}
}
then in your terminal enter this command
composer dump-autoload
it should fix your problem

How to use external PHP file in laravel blade.php file?

I want to include external PHP file (pdate.php) in Laravel and use it in blade.php file. How can I do it?
The PHP file imported in app\date\pdate.php folder and by using app_path() function in controller I try to send it in blade.php but there is error.
public function index(){
include_once(app_path() . '/date/pdate.php');
return view('/cashWithdraw/create');
}
When I use one variable of that file in blade.php I will get this error.
Undefined variable: today (View: E:\laravelProject\deal\resources\views\cashWithdraw\create.blade.php)
In composer.json file you just add needed files in “autoload” section – in a new entry called files:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/date/pdate.php"
]
},
after that run this command composer dump-autoload now you can use any function in this file globally
This can easily be done using the blade #include() helper. If you save your file as a pdate.blade.php file, for example in resources/views/date, then you can include it as follows:
Inside of cashWithdraw/create.blade.php:
#include("date/pdate")
The only catch is that the variables available in pdate.blade.php need to be defined, but that can be done in a number of ways:
Directly in pdate.blade.php:
#php $today = \Carbon\Carbon::now(); #endphp
In the controller that returns create.blade.php:
public function index(){
$today = \Carbon\Carbon::now();
return view('cashWithdraw.create')->with(["today" => $today]);
}
In the #includes within create.blade.php:
#include("date/pdate", ["today" => \Carbon\Carbon::now()])
You aren't passing any variables into your view. You will need to pass any variables generated by pdate into the view.
public function index(){
include_once(app_path() . '/date/pdate.php');
return view('/cashWithdraw/create', [
'today' => $today
]);
}
The only variables that will be available in your blade are the ones you pass in there.
If your file is a class, you can inject it into a view by using service injection as follows:
#inject('pdata', 'app\date\pdate')
then invoke any method. Assuming your class has one like getMyDate:
<div class="anything">
{{ $pdata->getMyDate() }}
</div>

Can't autoload a helper file - Laravel 5.3

I have a helper file located at
app/Helpers/Navigation.php
Helper file with namespace:
<?php
namespace App\Helpers;
class Navigation
{
public static function isActiveRoute($route, $output = 'active')
{
if (Route::currentRouteName() == $route) {
return $output;
}
}
}
i wanted to autoload this file . So in my composer.json i have this:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/Navigation.php"
]
},
In my view i want to do this:
<li class="{{ isActiveRoute('main') }}">
But i get the error:
Call to undefined function isActiveRoute()
Not sure what i'm doing wrong. I did composer dumpautoload when i changed the composer file. I tried installing composer again, that also didn't change anything.
i had the same issue, i'm assuming that you are using inspinia laravel version, so the problem is that they forgot to remove the file app/Helpers/Navigation.php
if you look the AppServiceProvider they are using the one in
'/../Http/Helpers/Helpers.php'
if you want to do Navigation::isActiveRoute then use the class file
but if you want to use {{ isActiveRoute('youRouteName') }} then you need to use the functions in '/../Http/Helpers/Helpers.php' and there is no need to use de composer.json (that was propossed in another solution for another problem)
i know i have the same feeling...
ps: Please sorry about my english
For a helpers file you don't want to be using a class. You would jut define the functions you want to use.
Also, it is good practice to wrap your function in a check to make sure that function doesn't already exist.
Replace the content of you Naviation.php with:
<?php
if (! function_exists('isActiveRoute')) {
/**
* [Description of this function]
*
* #param $route
* #param string $output
* #return string
*/
function isActiveRoute($route, $output = 'active')
{
if (Route::currentRouteName() == $route) {
return $output;
}
}
}
Hope this helps!
When your helper file is a class then there is no need to autoload it.
Just create an alias in config/app.php as:
'aliases' => [
...
'NavigationHelper' => App\Helpers\Navigation::class,
...
Use it in your Blade template as:
<li class="{{ NavigationHelper::isActiveRoute('main') }}">
At last, you can remove the following code from composer.json file and the run composer dumpautoload
"files": [
"app/Helpers/Navigation.php"
]

Where do I put Laravel 4 helper functions that can display flash messages?

I've written a simple display_messages() function that will search Session::get('errors') for flash data and echo it to the screen.
Where do I put this function? In Codeigniter, you had a helpers folder where you could stick all your little global helper methods.
As Usman suggested,
create a file /application/libraries/demo.php
define a class Demo() { inside it
call the function like so: {{ Demo::display() }}
Works because libraries and models are autoloaded in start.php line 76. I believe that filenames must match Classnames (note capital).
<?php
class Demo {
public static function display() {
if( !$message = Session::get('errors'))
$message = 'No Errors';
echo "<pre>print_r($message)</pre>";
}
}
Can't quite figure out why I had a problem using the classname Common, there may be a conflict (you could define a namespace if this were important)...
Create a folder helpers within your app folder and create a file application_helper.php. With such code:
// app/helpers/application_helper.php
function display_messages()
{
exit('Yes');
}
Then open your composer.json file in root. autoload app/helpers/application_helper.php with composer files.
"autoload": {
....
"files": [
"app/helpers/application_helper.php"
]
Done, you can now call display_messages().
Some autoloaders may require you to run composer dump command for the first time.
Thank you memeLab provided a very useful answer which helped me a lot. I just wanted to expand on his answer as the "libraries" folder was not an auto load directory, at least not in the release/current version of L4 I am using. Also the start.php seems to have been expanded to be the start folder with global.php, local.php, and artisan.php.
So to use your own classes for separate libraries or helpers with the L4 lazy auto loader you just have to include whichever folder you want to store these in to the global.php. For example I added a libraries folder to the directory list.
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
// this a custom path
app_path().'/libraries',
));
Then whatever class you define in that folder as classname.php can be called via CLASSNAME::methodName($someVar); in your controllers.
class CLASSNAME {
public static function methodName($someVar=NULL) {
// whatever you want to do...
return $message;
}
}
So in this fashion you can create a helper class and define different methods to use throughout your controllers. Also be careful defining regular functions outside of your Class in this manner will cause you grief because they will not work (because the class is not always loaded). (for example someFunctionName($someVar); instead of CLASSNAME::methodName($someVar);) If you want to create functions in this manner you would need to make sure the is loaded, however I will not elaborate on this because it is better practice to use the lazy loader classes for such things so you only load the classes you really need.
Thanks again to memeLab and Usman, I would not have gotten as far without their answers. :)
For loading Classes:
Create app/libraries/class/Message.php, and add class in file
class Message {
public static function display() {
}
}
Add "app/libraries/class" to composer.json
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/libraries/class"
]
},
Finally run composer dump-autoload in command line.
You can access that by Message::display()
For loading plain non-object php Functions:
Create app/libraries/function/display_messages.php, and add function in file
function display_messages() {
}
add one line in start/global.php
require app_path().'/libraries/function/display_messages.php';
You can access that just by display_messages()
Add this in app/start/global.php
require app_path().'/config/autoload.php';
require app_path().'/start/loader.php';
App::instance('loader',new loader($autoload));
create a new file loader.php in app/start and add:
class loader{
private $helpers = array();
public $autoload = array(
'helpers' => array()
);
function __construct($autoload = array()) {
if (!empty($autoload))
$this->autoload = $autoload;
foreach ($this->autoload as $key => $value)
{
$function = strtolower($key);
$this->$function($value);
}
}
function helpers($helpers=array())
{
if (!is_array($helpers))
$helpers = explode(",",$helpers);
foreach ($helpers as $key => $value) {
$this->helper($value);
}
}
function helper($helper = '',$path = '/')
{
$folder = app_path().'/helpers'.$path;
if (file_exists($folder.$helper.'.php') && !in_array($helper, $this->helpers)){
$this->helpers[] = $helper;
require $folder.$helper.'.php';
}
else{
$segments = explode('/',$helper);
if (is_dir($folder.$segments[0])){
array_shift($segments);
$this->helper($segments,$path.$segments[0].'/');
}
}
}
}
create a new file autoload.php in app/config and add:
$autoload['helpers'] = array('functions'); // my autoload helpers!
create a new folder helpers in app/ , add your helper files. ( es. myhelper.php )
function myhelper()
{
echo 'helper';
}
in your controller add:
App::make('loader')->helper('myhelper');
myhelper();
In L3, I would normally create a application/libraries/helpers.php file, and require_once() it in my application/start.php. Similar to how L3 has a laravel/helpers.php file.
I'm assuming there is something similar you can do in L4.
EDIT: Just looking at the source, app/start/local.php seems like it might be the place.
I used this tutorial and i think is the easiest method: http://laravel-recipes.com/recipes/50/creating-a-helpers-file
First create the file app/helpers.php
Then either load it at the bottom of app\start\global.php as follows.
// at the bottom of the file
require app_path().'/helpers.php';
Or change your composer.json file and dump the autoloader.
{
"autoload": {
"files": [
"app/helpers.php"
]
}
}
$ composer dump-auto
then you can write your functions in helpers.php and call them from anywhere
function myfunction($result){
return $result;
}
open root_folder/vendor/laravel/framework/src/Illuminate/Support/helpers.php
and you can add your function
if ( ! function_exists('display_messages'))
{
function display_messages()
{
return ...
}
}

Categories