Laravel | Class not Found - laravel

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;

Related

Why I can not call Implementation method from library class?

In laravel 9 app I created class app/Implementations/LocalStorageUploadedFileManagement.php :
<?php
namespace App\Implementations;
use App\Interfaces\UploadedFileManagement;
...
use Intervention\Image\Facades\Image as Image;
class LocalStorageUploadedFileManagement implements UploadedFileManagement
{
...
public function getImageFileDetails(string $itemId, string $image = null, string $itemUploadsDirectory = '',
bool $skipNonExistingFile = false): array {
\Log::info('++ getImageFileDetails$image ::');
\Log::info( $image );
}
...
and Interface class in app/Interfaces/UploadedFileManagement.php :
<?php
namespace App\Interfaces;
use Illuminate\Http\Request;
interface UploadedFileManagement
{
...
public function getImageFileDetails(string $itemId, string $image = null, string $itemUploadsDirectory = '',
bool $skipNonExistingFile = false): array;
}
In app/Providers/AppServiceProvider.php I have:
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind('App\Interfaces\UploadedFileManagement', 'App\Implementations\LocalStorageUploadedFileManagement');
}
so I can use it in my controller app/Http/Controllers/Admin/ProductController.php:
<?php
namespace App\Http\Controllers\Admin;
...
use App\Interfaces\UploadedFileManagement;
class ProductController extends Controller // http://local-mng-products.com/admin/products
{
public function __construct()
{
}
public function edit(string $productId, UploadedFileManagement $uploadedFileManagement)
{
...
$productImgProps = $uploadedFileManagement->getImageFileDetails(
itemId : $product->_id,
itemUploadsDirectory : Product::getUploadsProductDir(),
image : $product->image,
skipNonExistingFile : true);
...
abd it works ok
But I got error :
Cannot instantiate interface App\Interfaces\UploadedFileManagement
when I try to use UploadedFileManagement in library app/Library/ReportProduct.php class :
<?php
namespace App\Library;
use App\Interfaces\UploadedFileManagement;
...
class ReportProduct
{
public function getImageProps()
{
$uploadedFileManagement= new UploadedFileManagement(); // This line raised the error
$imgProps = $uploadedFileManagement->getImageFileDetails($this->product->_id, $this->product->image, Product::getUploadsProductDir(),true);
return $imgProps;
}
getImageProps method is called from ProductCardReport component, which I created with command :
php artisan make:component ProductCardReport
and it has in file app/View/Components/ProductCardReport.php :
<?php
namespace App\View\Components;
use App\Library\ReportProduct;
use Illuminate\View\Component;
class ProductCardReport extends Component
{
public string $productId;
public function __construct(string $productId)
{
$this->productId = $productId;
}
public function render()
{
$reportProduct = new ReportProduct($this->productId);
$reportProduct->loadProduct();
$productData = $reportProduct->getProductData(true);
$productImgProps = $reportProduct->getImageProps();
...
Why I got error in ReportProduct.php class on using of UploadedFileManagement service?
How that can be done ?
MODIFIED BLOCK :
I tried to inject it in the same way I did in ProductController edit function.
But I failed as If I try to edit app/Library/ReportProduct.php with similar injection :
<?php
namespace App\Library;
use App\Interfaces\UploadedFileManagement;
...
class ReportProduct
{
public function __construct(Product | string $product, UploadedFileManagement $uploadedFileManagement = null)
{
$this->uploadedFileManagement = $uploadedFileManagement;
...
But as I create ReportProduct and call getImageProps from app/View/Components/ProductCardReport.php component
I need to UploadedFileManagement class from somewhere for the 1st time . I can not inject
UploadedFileManagement in app/View/Components/ProductCardReport.php.
Not shure how injection works here and how can I use it in chain Component->customClass?
Thanks!
Your UploadedFileManagement is an object interface and interfaces are not instantiable (a fancy way of saying you can't create an instance of an interface - i.e. new UploadedFileManagement()).
Binding an interface and an implementation in the Laravel service container doesn't magically transform your code to use the implementation wherever you have made use of the interface. All it does is tell Laravel how to resolve a dependency when it encounters one.
To clarify this when you run your application
$service = new UploadedFileManagement();
Doesn't get converted to
$service = new LocalStorageUploadedFileManagement();
That is not how dependency injection or the service container work.
If you want to make use of your LocalStorageUploadedFileManagement() class in the ReportProduct class, you will need to inject it in the same way you have done with your ProductController edit function.
Valid decision is :
$uploadedFileManagement= app(UploadedFileManagement::class);
$productImgProps = $uploadedFileManagement->getImageFileDetails(
itemId : $product->_id,
itemUploadsDirectory : Product::getUploadsProductDir(),
image : $product->image,
skipNonExistingFile : true);

How to use namespace in Laravel in controller?

I have a custom class in App/Helpers/regexValidation.php:
<?
namespace App\Helpers;
class RegexValidation
{
public static function isCVC($str)
{
$re = '/^[0-9]{3,4}$/s';
preg_match($re, $str, $matches);
return $matches;
}
}
I try to use it in controller:
<?php
namespace App\Http\Controllers;
use App\Helpers\RegexValidation;
public function detectfile(Request $request)
{
$cvc = RegexValidation::isCVC(555);
}
When I call this method from route Laravel I get:
Error: read ECONNRESET
If comment this line $cvc = RegexValidation::isCVC(555); it works.
What do I do wrong?
I think you are having a PSR4 Error,
I have a custom class in App/Helpers/regexValidation.php
Rename that file to PascalCase as RegexValidation.php
after renaming run
composer dumpautoload
And it should work.

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.

Laravel : Class controller does not exist

I have created a simple controller and define a function. But when i run this it returns an error that controller does not exist.
In my web.php assign a route.
<?php
Route::get('/', function () { return view('front.welcome'); });
Route::get('plan','PlanController#PlanActivity')->name('plan');
On otherside in my controller my code:
<?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;
class PlanController extends Controller {
public function PlanActivity()
{
dd("hello");
//return view('admin.index');
}
}
This controller created on App\Http\Controllers\Front - on front folder
Error :
ReflectionException (-1)
Class App\Http\Controllers\PlanController does not exist
Add Front part to:
Route::get('plan', 'Front\PlanController#PlanActivity')->name('plan');
Also, change the top of the controller to:
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
And run composer du.
From the docs:
By default, the RouteServiceProvider includes your route files within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.
First when defining route, make sure to use the correct path for the controller. the correct is:
Route::get('plan','Front/PlanController#PlanActivity')->name('plan');
Second you have imported Controller Class as BaseController. so you should extends BaseController not Controller:
class PlanController extends BaseController {
public function PlanActivity()
{
dd("hello");
//return view('admin.index');
}
}

Laravel 5.2 custom helper not found

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

Resources