Laravel 5.2 custom helper not found - laravel

I have created app/Http/helpers.php
if (!function_exists('getLocation')) {
function getLocation($request)
{
return 'test';
}
I have added files section in composer.json autoload
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Http/helpers.php"
]
},
Here is my controller :
namespace App\Http\Controllers;
use App\Jobs\ChangeLocale;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Log;
class HomeController extends Controller
{
public function index(Request $request)
{
$data['location'] = getLocation($request);
}
}
When I call the function in controller as getLocation($request); it is saying "Call to undefined function App\Http\Controllers\getLocation()"
This is working fine in my local , but not on remote server. What am I missing in my remote server. Tried composer install and composer dump-autoload.
UPDATE:
The helper file is not getting listed in vendor/composer/autoload_files.php

On server, you need to execute:
composer dumpautoload
because it is not found on vendor/autoload.php

Try like this,
create Helpers directory inside the app directory.
create a Example.php file inside the Helpers directory
create a alieas for this file at config/app.php file
Ex: 'Example' => App\Helpers\Example::class,
The code in the Example.php like follows,
<?php
namespace App\Helpers;
class Example
{
static function exampleMethod()
{
return "I am helper";
}
}
Using the above Example helper in Controller files like follows,
<?php
namespace App\Http\Controllers;
use App\Helpers\Example;
class HomeController extends Controller
{
public function index(Request $request)
{
return Example::exampleMethod();
}
}
Using the above Example helper in blade view files like follows,
<div>{{ Example::exampleMethod()}}</div>
This will help you to get solution.

Make Sure the structure of the Helper.php is correct...
<?php
//no namespace, no classes
//classes are not helpers
if ( !function_exists('nextStage') ) {
function nextStage($currentStage) {
//if you need to access a class, use complete namespace
return \App\Models\Stage::where('id',$currentStage)->first()->next_stage;
}
}
More help on Laracast found here

Related

How can I fix the namespace error when using classes within the app folder?

I am upgrading a legacy laravel application from Laravel 5 to 8 and ran into a brick wall. None of my service providers work, and I cannot figure out why.
Previous Structure
app
-->Services
------>Stripe
Within each service provider folder, I'd create three files like so:
Stripe.php
StripeFacade.php
StripeServiceProvider.php
within stripe.php
<?php
namespace app\Services\Stripe;
class Stripe
{
}
?>
within StripeFacade.php
<?php
namespace app\Services\Stripe;
use Illuminate\Support\Facades\Facade;
class StripeFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'Stripe';
}
}
within StripeServiceProvider.php
<?php
namespace app\Services\Stripe;
use Illuminate\Support\ServiceProvider;
class StripeServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('Stripe', function($app) {
return new Stripe();
});
}
}
in my Config/app.php file, I'd register the service provider and facade like so:
'providers' => [
app\Services\Stripe\StripeServiceProvider::class,
],
'aliases' => [
'Stripe' => app\Services\Stripe\StripeFacade::class,
]
In my controller, I'd call the Stripe service as
use Stripe;
...
public function example(){
$auth = Stripe::auth();
}
Then I'd get this error in the Config/app.php file
Class "app\Services\Stripe\StripeServiceProvider" not found
I tried adding the Services directory to my psr-4 and didn't seem to get any luck, even after dumping configs and autoload.
"autoload": {
"psr-4": {
"App\\": "app/",
"Services\\": "app/Services",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
any help? :)
In your comment, you posted an error:
Class App\Services\Stripe\StripeServiceProvider located in ./app/Services /Stripe/StripeServiceProvider.php does not comply with psr-4 autoloading standard. Skipping.
I noticed an extra space in ./app/Services /Stripe.
Perhaps you have created the Services / directory with a space at the end.
Some improvements are to rename app\ to App\ and remove the "Services\\": line from your composer.json. Run composer dump-autoload after these changes.
Use the below code
namespace App\Services\Stripe;
use App\Services\Stripe\StripeServiceProvider::class

Laravel | Class not Found

I would like ot integer an externe class with two functions into my laravel project. This externe class serves for e-payment.
I created a new folder in \App named xxx then my php file named xxx.php.
My path is
\App\xxx\xxx.php
When i would like to call this class in XController using this code :
<?php
namespace App\Http\Controllers;
use App\xxx\xxx;
class XController extends Controller
{
public function Send(Request $request){
$function = new xxx;
};
}
A got an Error : Class 'App\xxx\xxx' not found
my xxx.php code is like that :
<?php
namespace App;
class xxx
{
public function function($data)
{
return ;
}
}
My route :
Route::get('/send', 'XController#Send');
Thank you in advance !
Correct the namespace in your class file Xxx.php
<?php
namespace App\Xxx;
class Xxx
{
public function function($data)
{
return ;
}
}
and run this command in your console
composer dump-autoload
Laravel uses PSR-4 autoloading, so you should ensure that your classes and folders are capitalised. You can read up more on PSR-4 here - https://www.php-fig.org/psr/psr-4/
In your case the folder should be Xxx instead of xxx and your file should be called Xxx instead of xxx.
At the same time you also need to update the namespace on the Xxx.php file:
<?php
namespace App\Xxx;
class Xxx
{
public function function($data)
{
return ;
}
}
Then within your controller you can update your use statement and the method.
<?php
namespace App\Http\Controllers;
use App\Xxx\Xxx;
class XController extends Controller
{
public function Send(Request $request){
$function = new Xxx;
}
}
I hope this helps.
in xxx.php file namespace should be like this :
namespace App\folderName; // App\xxx;
and then run
php artisan config:cache;

After adding a new directory into controllers, fatal error thrown

I am new to Laravel and after I added a new directory to the controllers viz, Admin, I updated the namespace also updated routes but somehow, I am getting a fatal error exception. Please help me figure out the problem
App->Http->Controllers->Admin
<?php
namespace App\Http\Controllers\Admin;
class AdminController extends Controller
{
public function index()
{
echo "admin controller";
}
}
routes.php
Route::get('/admin', 'Admin\AdminController#index');
snapshot of directory structure
try
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
class AdminController extends Controller
{
public function index()
{
echo "admin controller";
}
}
Note the "use" statement. I suspect that Laravel is looking for the Controller class, which this controller extends, but is unable to find it because of that missing statement.

Serious issues understanding namespacing in Laravel 5

I am having problems understanding namespacing. It just feels so stupid that for every Facade or helper I want to include, I need to included it in the controller file.
So, say I have this exerpt of my controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Auction;
use App\Bid;
use App\BidBuy;
use App\Http;
use Redirect;
use Session;
use Illuminate\Http\Request;
use Omnipay\Omnipay;
class PayPalController extends Controller {
private $data;
public function getPayment()
{
redirectIfNotLoggedIn();
}
The line with redirectIfNotLoggedIn(); is a function I want to call that is stored in App/Http/helpers.php
This is the file: helpers.php
<?php namespace App\Http;
class HelperFunctions {
// Filter for guest only pages
public function redirectIfLoggedIn() {
if (Session::has('steamid')) {
return Redirect::to('/');
} else {
return false;
}
}
// Filter for logged users only pages
public function redirectIfNotLoggedIn() {
if (Session::has('steamid')) {
return true;
} else {
return Redirect::to('/');
}
}
}
Back in the controller I have included: use App\Http;
When I go to call that function I get this:
FatalErrorException in PayPalController.php line 20:
Call to undefined function App\Http\Controllers\redirectIfNotLoggedIn()
EDIT:
Now I have: HelperFunctions.php located at App/Helpers/HelperFunctions.php:
<?php namespace App\Helpers;
use Session;
use Redirect;
// Filter for guest only pages
function redirectIfLoggedIn() {
if (Session::has('steamid')) {
return Redirect::to('/');
} else {
return false;
}
}
// Filter for logged users only pages
function redirectIfNotLoggedIn() {
if (Session::has('steamid')) {
return true;
} else {
return Redirect::to('/');
}
}
Excerpt of composer.json:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"psr-0": {
"Ignited\\LaravelOmnipay": "src/"
},
"files": [
"app/Helpers/HelperFunctions.php"
]
},
And this is my controller:
<?php namespace App\Http\Controllers;
//use App\Helpers\HelperFunctions;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Auction;
use App\Bid;
use App\BidBuy;
use Redirect;
use Session;
use Illuminate\Http\Request;
use Omnipay\Omnipay;
class PayPalController extends Controller {
private $data;
public function getPayment(\App\Helpers\HelperFunctions $helper)
{
$helper->redirectIfNotLoggedIn();
}
.. rest of the controller code here ..
}
Do not use helpers for this. You are violating pretty much everything related to OOP in doing so.
Instead, use Middleware.
In your controller, simply require the auth middleware:
public function __construct()
{
$this->middleware("auth");
}
You are trying to solve a solved problem. If you need to do something before executing a route/controller method, middleware (the Laravel 5 replacement for route filters) should be used.
You will likely have to customise your own middleware, however, then add it to the middleware array in app/Http/Kernel.php. Just use php artisan make:middleware CustomAuthMiddleware.
You could use your HelperFunctions via method injection in your controller. Like this:
public function getPayment(\App\Http\HelperFunctions $helper)
{
$helper->redirectIfNotLoggedIn();
}
It's not tested.

Laravel 4 - Class resolution not working

I have a controller:
<?php namespace controllers;
class XController extends \BaseController {
public function loadHome() {
$view = new \views\XView;
$html = $view->Build();
return $html;
}
}
And a View
<?php namespace views;
class XView{
public function Build()
{
return "oi oi";
}
}
?>
Also, I've added this line in my classloader in my global.php
app_path().'/views',
and have tried
composer dump-autoload
It just keeps giving me
Class 'views\XView' not found
Any ideas?
P.S. I'm intentionally not using Blade.
Composer won't help if you don't use composer.json. So, edit your composer.json and add your views folder to it:
"autoload": {
"classmap": [
...
"views"
],
},
Then you do
composer dump-autoload
And check the file
vendor/composer/autoload_classmap.php
Your classes must appear there, otherwise it won't work.

Resources