Laravel 4 - Class resolution not working - laravel

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.

Related

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.

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;

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

Laravel: Controller does not exist

I added new controller in /app/controllers/admin/ folder and added the route in /app/routes.php file as well. Then i run the following command to autoload them
php artisan dump-autoload
I got the following error
Mcrypt PHP extension required.
I followed instruction given at https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql and able to resolve the mcrypt issue.
After that i run the php artisan dump-autoload command but still getting following error
{"error":{"type":"ReflectionException","message":"Class CoursesController does not exist","file":"\/var\/www\/html\/vendor\/laravel\/framework\/src\/Illuminate\/Container\/Container.php","line":504}}
Here is code of my routes.php file
Route::group(array('before' => 'adminauth', 'except' => array('/admin/login', '/admin/logout')), function() {
Route::resource('/admin/courses', 'CoursesController');
Route::resource('/admin/teachers', 'TeachersController');
Route::resource('/admin/subjects', 'SubjectsController');
});
Here is code of CoursesController.php file
<?php
class CoursesController extends BaseController
{
public function index()
{
$courses = Course::where('is_deleted', 0)->get();
return View::make('admin.courses.index', compact('courses'));
}
public function create()
{
return View::make('admin.courses.create');
}
public function store()
{
$validator = Validator::make($data = Input::all(), Course::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
Course::create($data);
return Response::json(array('message'=>'Course created successfully','status'=>'success'));
}
}
public function edit($id)
{
$course = Course::find($id);
return View::make('admin.courses.edit', compact('course'));
}
public function update($id)
{
$course = Course::findOrFail($id);
$validator = Validator::make($data = Input::all(), Course::editRules($id));
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
$course->update($data);
return Response::json(array('message'=>'Course updated successfully','status'=>'success'));
}
}
public function destroy($id)
{
Course::findOrFail($id)->update(array('is_deleted' => '1'));
return Response::json(array('message'=>'Course deleted successfully','status'=>'success'));
}
}
Did you add autoload classmap to composer.json file?
Open your composer.json file and add
"autoload": {
"classmap": [
"app/controllers/admin",
]
}
if you add folders inside controllers, you need to add it to composer.json file. Then run
composer dumpautoload
OR ALTERNATIVE
go to app/start/global.php and add
ClassLoader::addDirectories(array(
app_path().'/controllers/admin',
));
2021 answer (Laravel 8.5)
In your controller;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login(Request $request){
return "login";
}
}
In your routes;
use App\Http\Controllers\AuthController;
Route::post('/login', [AuthController::class, 'login']);
Doc = https://laravel.com/docs/8.x/routing#the-default-route-files
In my case, in the top of my controller code i add this line :
namespace App\Http\Controllers\CustomFolder\ControllerClassName;
and my problem is solved
We can create controller via command line.
php artisan make:controller nameController --plain.
Before Laravel 5, make namespace is not available. Instead, this works
php artisan controller:make nameController
Execute your command inside your project directory and then create your function.
Don't forget to do:
php artisan route:clear
In my case this was the solution when I got this error after making a route code change.
In my case, I had to change the route file from this:
Route::get('/','SessionController#accessSessionData');
to this:
Route::get('/','App\Http\Controllers\SessionController#accessSessionData');
then clearing the cache with this:
php artisan route:clear
made things work.
A bit late but in my experience adding this to the RouteServiceProvider.php solves the problem
protected $namespace = 'App\Http\Controllers';
I think your problem has already been fixed. But this is what did.
Structure
Http
.Auth
.CustomControllerFolder
-> CustomController.php
to get this working
in your route file make sure you use the correct name space
for eg:
Route::group(['namespace'=>'CustomControllerFolder','prefix'=>'prefix'],
function() {
//define your route here
}
Also dont forget to use namespace App\Http\Controllers\CustomControllerFolder in your controller.
That should fix the issue.
Thanks
I just had this issue because I renamed a file from EmployeeRequestContoller to EmployeeRequestsContoller, but when I renamed it I missed the .php extension!
When I reran php artisan make:controller EmployeeRequestsContoller just to be sure I wasn't going crazy and the file showed up I could clearly see the mistake:
/EmployeeRequestsContoller
/EmployeeRequestsContoller.php
Make sure you have the extension if you've renamed!
I use Laravel 9 this is the way we should use controllers
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Sometimes we are missing namespace App\Http\Controllers; on top of our controller code.
In my case, I have several backup files of admin and home controllers renamed with different dates and we ran a composer update on top of it and it gave us an error
after I removed the other older controller files and re-ran the composer update fixed my issue.
- Clue - composer update command gave us a warning.
Generating optimized autoload files
Warning: Ambiguous class resolution, "App\Http\Controllers\HomeController" was found in both "app/core/app/Http/Controllers/HomeController(25-OCT).php" and "app/core/app/Http/Controllers/HomeController.php", the first will be used.
Warning: Ambiguous class resolution, "App\Http\Controllers\AdminController" was found in both "app/core/app/Http/Controllers/AdminController(25-OCT).php" and "app/core/app/Http/Controllers/AdminController.php", the first will be used.
Use full namespace inside web.php
Route::resource('myusers','App\Http\Controllers\MyUserController');

Resources