Reflection Exception : Class ClassName doesn't exist - php

I am using Laravel 5.5. I have added a custom directory inside App folder in my workspace. So, the folder structure is:
Inside App\Bishwa\Transformers there are two PHP files:
Transformer.php
LessonTransformer.php
Those files look like follows:
Transformer.php
<?php
namespace Bishwa;
abstract class Transformer {
public function transformCollection(array $items){
return array_map([$this, 'transform'], $items);
}
public abstract function transform($item);
}
LessonTransformer.php
<?php
namespace Bishwa;
class LessonTransformer extends Transformer {
public function transform($lesson){
return [
'title' => $lesson['title'],
'body' => $lesson['body'],
'active' => (boolean)$lesson['some_bool']
];
}
}
Then Inside LessonsController.php I have the following:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Lesson;
use Bishwa\LessonTransformer;
class LessonsController extends Controller
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer){
dd('ok');
}
While running action of the controller, It gave me an error message saying:
Reflection Exception: Class Bishwa\LessonTransformer does not exist
I have tried composer dump-autoload, restarting the server again but none of them helped. Am I doing wrong while Namespacing or What?

Change your namespace of the files in your custom directory to App\Bishwa.

Well thanks to Jerodev and Jack. Since, both of them were write I decided to write myself a combined solution to this problem.
1st Solution:
In case of custom namespaces and custom classes I have to include the path to classname in Composer.json file in the following portion:
"autoload": {
"classmap": [
"database/seeds",
"database/factories",
"app/Bishwa/Transformers"
],
"psr-4": {
"App\\": "app/"
}
2nd Solution:
Changing NameSpace of my files to custom directory App\Bishwa .
Namespace of transformer.php and LessonTransformer.php now becomes:
namespace App\Bishwa\Transformers;
While using in LessonsController:
use App\Bishwa\Transformers\LessonTransformer;
Once again, big thanks to Jerodev and Jack. Its my silly mistake, that I couldn't figure that out.

Related

Class Not Found in PHP Laravel 6.x when another class extends

I always get the class not found exception in php laravel 6 when i create a class and extend a parent class named A which is located in the same directory.
However, another child class that is located in same directory could extend class A successfully.
In addition, i couldn't also instantiate the class A due to class not found exception in another .php file.
Please help me on this.
Thanks in an advance.
Parent class: myContext
<?php
namespace config\models;
class myContext {
public static $conn;
...
}
Class myUser: extension is fine.
<?php
namespace config\models;
class myUser extends myContext {
private $name;
...
}
Class oauth: extension returns myContext class not found.
<?php
namespace config\models;
class oauth extends myContext {
private $user;
}
Instantiate the class - returns class not found.
<?php
use config\models\myContext as context;
$cont = new context();
Check whether the namespace is added correctly when the parent class is imported.
Refer
https://www.quora.com/What-is-namespaces-and-use-in-Laravel
external classes and PHP files in Laravel - Class not found
Laravel - Model Class not found
Laravel 6: Class 'Form' not found
To get the provided example codes to work you need to use require_once
<?php
require_once('models/myContext.php');
use app\config\models\myContext as context;
$test = new context();
A search on SO brought me to this source
You try to add this line of code in the composer.json file, then execute the composer dumpautoload command on the command line
In composer.json file,
"autoload": {
"psr-4": {
"App\\": "app/",
"config\\models\\": "config/models"
},
"classmap": [
"database/seeds",
"database/factories"
]
},
After that composer dump-autoload.
have you add autoload for config/ folder in composer.json. Laravel only default autoload for app/

How to add custom class in laravel 5.4.10

I am new in laravel.
I am writing following code in the controller method.
include_once(app_path() .'/Classes/Pgp_2fa.php');
$pgp = new Pgp_2fa();
Following errors are shown.
FatalThrowableError in AuthController.php line 146: Class
'App\Http\Controllers\Pgp_2fa' not found
You have to use the correct namespace for your class.
If you are not using any namespace, you should add a \ in front of the class to let php know that the class exists in the root namespace. Otherwise php will look in the current namespace which is App\Http\Controllers when you are in a controller.
$pgp = new \Pgp_2fa();
This is not just Laravel behavior but php in general.
When you add new classes there are couple way to use them. (I mean, load them)
If your classes has unique name and don't use namespace, then you can add backslash \ start of the class.
$class = new \Pgp_2fa;
But if you want to define them namespaces and use with same name so
many times, then you have to add these classes in composer.json. Open your
composer.json and come into "autoload" section and define class
directory in classmap
"autoload": {
"classmap": [
"database/seeds",
"database/factories",
"app/Classes", // so all classes in this directory are going to load
],
And don't forget to say composer dump-autoload after these changes and creating new classes
If you don't want to dump your composer when you add a new class,
then you may want add those classes inside of the psr-4 section in composer
"autoload": {
"psr-4": {
"App\\": "app/",
"App\\Classes\\": "app/Classes",
}
},
you need to add namespace for your custom class
or just add slash on your class name. like :
$pgp = new \Pgp_2fa();
You can call inside the constructor like below, and you can use the
$Pgp_2fa variable in remaining function
class controllername extends Controller
{
public function __construct(Route $route,Request $request)
{
$Pgp_2fa = new \Pgp_2fa();
}
}
You can easily add your custom classes by added it to Composer's autoload array. Go to composer.json and add it to:
"autoload": {
"files": [
"app\\Classes\\Pgp_2fa.php"
]
},
Now in your app folder, under classes folder add your Pgp_2fa.php file which will have your class. You can use it anywhere you want, it should be automatically auto-load-ed.
After adding your class write command:
composer dumpautoload to refresh autoload class mapping.
For example, There is our class Common.php in a directory called Mylibs in app directory.
app/mylibs/Common.php
we need to namespace App\Mylibs;
namespace App\Mylibs;
class Common {
public function getSite() {
return 'AmirHome.com';
}
}
Now, you can access this class using the namespace within your classes just like other Laravel classes.
use App\Mylibs\Common
in Controller:
namespace App\Http\Controllers;
use App\Mylibs\Common;
class TestController extends Controller {
protected $common;
public function __construct(Common $common) {
$this->common = $common;
}
public function index() {
echo $this->common->getSite();
}
}

How to use traits in Laravel models?

Hello i'm laravel beginner
I want to make trait and use it in my model but at run time i got error that the trait is not found
my trait :
namespace App;
use Illuminate\Support\Facades\Schema;
trait GeneralModel
{
public static function testStaticFunction()
{
dd('test');
}
}
my model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use GeneralModel;
}
my controller
namespace App\Http\Controllers;
use App\Comment;
class SearchController extends Controller
{
public function find()
{
Comment::testStaticFunction();
}
}
error received
Trait 'App\GeneralModel' not found
In composer.json add this:
"autoload" : {
"classmap": [
"database/seeds",
"database/factories"
],
"files" : [
"app/GeneralModel.php" // <----------- ADD THIS
],
"psr-4" : {
"App\\": "app/"
}},
Then run composer dump-autoload
Please check the GeneralModel.php in app folder. And execute the below command in your project root path.
php artisan dump-autoload
You Have to Use
Composer dump-autoload
In Your command line
hope it's help

Getting "Class 'app\Http\Controllers\Controller' not found" in Laravel 5.1

I'm quite new to Laravel and when I am going through a tutorial when I encountered this error. This is my code in 'testController.php'.
<?php
namespace app\Http\Controllers;
use app\Http\Controllers\Controller;
class testController extends \app\Http\Controllers\Controller {
public function getAbout()
{
return view('Learning.about') ;
}
public function getHome()
{
return view('Learning.index');
}
}
And this is my 'routes.php'.
<?php
Route::get('test', [
'as' => 'test',
'uses' => 'testController#getHome',
]);
Route::get('about', [
'as' => 'about',
'uses' => 'testController#getAbout',
]);
I am getting this error:
Class 'app\Http\Controllers\Controller' not found
How can I fix this error?
Let's go through this step by step.
1. Check autoload directive on composer.json
Open composer.json file on your project root directory. Locate the the autoload section. It should be looking like this:
{
...
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
}
Make sure you have this configuration under the psr-4 option:
"App\\": "app/"
This configuration tells the composer that we want to autoload all classes inside the app directory using psr-4 convention and places it under the App namespace.
2. Update your controller
First, your controller file name should be in CamelCase style. So we have to renamed it to TestController.php. Make sure that it's saved under app/Http/Controllers directory.
Now open your TestController.php file, we have to capitalize the namespace and class name like so:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class TestController extends Controller {
public function getAbout()
{
return view('Learning.about') ;
}
public function getHome()
{
return view('Learning.index');
}
}
Note that we also turn this line:
class testController extends \app\Http\Controllers\Controller
Into:
class TestController extends Controller
Since we already import the base Controller class, we don't have to specify the fully qualified name. We imported the Controller class using the use keyword:
use App\Http\Controllers\Controller;
Save your TestController.php file.
3. Update your routes file
Now we have to update our app\Http\routes.php file. We just need to capitalize the controller name:
<?php
Route::get('test', ['uses' => 'TestController#getHome', 'as' => 'test']);
Route::get('about', ['uses' => 'TestController#getAbout', 'as' => 'about']);
4 Update your autoloader
Now the last thing to do. Open your terminal / command prompt. Go to your project directory and run the following command:
composer dump-autoload
This command will update the autoloader file (Read more here).
Now if you open up your browser and hit /test route, you should see the content from resources/views/Learning/index.blade.
Use correct namespace:
namespace App\Http\Controllers;
// Remove: use app\Http\Controllers\Controller;
class testController extends Controller {
According to my experience in Laravel projects, the namespaces starts with the capital A of App used in namespace, you should try to change your code to this:
namespace App\Http\Controllers;
class testController extends Controller { }
Also check if the controller - App\Http\Controllers\Controller lies in the same namespace as mentioned in your code.
Include this at the top of your Controller file. This fixed it for me.
namespace App\Http\Controllers;
In some cases the problem is that the framework is not able to instantiate your given controller class. This can happen for example if you are using a sub-folder under Controllers and that when you are extending the Controller.php class, you did not provide the use statement to that definition*. Other run-time errors may also cause this.
*Which is now required since your own controller is not at the root of the Controller folder anymore.

How to keep seeder files separate and clean in laravel?

I want to keep my seeder files separate. for example UsersTableSeeder.php , PostsTableSeeder.php and then call them in main seeder file (DatabaseSeeder.php) :
Example:
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(PostsTableSeeder::class);
}
}
usersTableSeeder.php :
<?php namespace App\Seeds;
use Illuminate\Database\Seeder;
use App\User;
class UserTableSeeder extends Seeder {
public function run()
{
//DB::table('users')->delete();
// user1
User::create(array(
'name' => 'ahmad',
'email' => 'ahmad#ahmad.com',
'password' => 'ahmad'
));
}
}
my UsersTableSeeder.php and PostsTableSeeder.php files are in the same
directory that DatabaseSeeder.php is.
should I use psr-4 autoloading ? how?
Composer.json configuration
composer.json has a autoload key to configure additional autoload paths.
You can give it a try:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
]
}
Example from my composer.json
Remove the namespace line from your seeder classes. They are found by the classmap entries now.
Explicit namespaces
OR
Keep the namespaces and add them in calls to ->call().
Wherever you write a classname you can fully qualify the class with its namespace (should be \database\seeds\YourClass::class, which can depend on your composer.json settings), or add a use statement at the beginning of the file.
You may have to run composer dump-autoload. It worked for me.
As a side note, it'd be cleaner to use PSR-4 for seeds and migrations (tests already do).

Categories