Troubleshooting referencing a model in a laravel controller - php

I've been trying unsuccessfully to resolve an error in a laravel 5.2 app (carfreak).
FatalErrorException in PropertyController.php line 85:
Class 'App\Models\CarModel' not found
I have moved the default user model to a folder app/models and made the necessary changes so that it's all working fine.
Now I have a new controller CarController, and a new model, CarModel that are just not working. It seems to be such a simple problem with namespaces, but I am unable to resolve it.
is the model in the models folder? Yes. carfreak\app\Models\CarModel.php
is the controller namespace correct? Yes... namespace carfreak\Http\Controllers;
does the controller reference the model? Yes...use App\Models\CarModel;
is the model namespace correct? Yes... namespace carfreak\Models;
I am able to create different versions of the error by playing with the CarController but no permutation I can think of has worked.
EDIT: Controller and Model added...
EDIT: More details added:
The irony of this is that I can php artisan make:model sanityCheck and it will create a model in the \app root (i.e. not in app\models)... and that model can be called just fine. If I put my CarController back in the root, and change it's namespace appropriately, it still doesn't work. It's almost like I have some stupid spelling error in the class name or something, but I've copied and pasted class names into my filename, class declaration, "use" declarations, etc. and it. still. doesnt. work. Aargh!
//this is carModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CarModel extends Model
{
//
/**
* The attributes that are mass assignable.
* #var array
*/
protected $fillable = [
'colourOfCar',
];
}
//this is carController
<?php
namespace carfreak\Http\Controllers;
use Illuminate\Http\Request;
//use \carfreak\app\Models\CarModel;
use App\Models\CarModel;
class CarController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'CarColour' => 'required|max:50'
));
// store in the database
$newCar = new CarModel;
dd($request);
}
}

This looks wrong use \carfreak\app\Models\CarModel; should be use App\Models\CarModel in this is carController
Casing is important on linux. The namespace generally is used in a PSR Aloader to find the file. And Linux filesystem is case sensitive. So the CareModel.php file should be located in App/Models/CarModel.php
But I never used Laravel...

Well, here it is. I solved it by asking myself this question: If I'm having so much trouble namespacing, referencing and organising my models, then maybe I can get artisan to do it for me.
The post that got me thinking differently was Mansoor Akhtar's advice here: How do I instruct artisan to save model to specific directory?
Get artisan to make the model in the right place first time.
php artisan make:model Models/CarModel
In the Controller, reference the model correctly
use name-of-app\Models\CarModel;
There may or may not be cache flushing involved in my problem. I was eventially restarting my XAMPP after every change to ensure no caching was involved. I also tried
php artisan cache:clear

Related

Problem with packages after Laravel namespace change to App\Models

So I used the namespace models shift to make the change from App to App\Models.
One of the packages in use (Ticketit) is calls App\User in it and I need a way to override this.
The offending file is:
\vendor\kordy\ticketit\src\Models\Agent.php
How can I override the "use App\user;" line there?
From what I am looking at in the source code, that is hardcoded, so you cannot do anything then... I am not sure if you could "fake" the App\User to point to App\Models\User using composer but that would be nasty, same if you created a class on inside app folder with name User and it only extends the model like this:
namespace App;
use App\Models\User as UserModel;
class User extends UserModel { }
That is nasty but maybe is a solution for you...
Edit: If you read carefully the documentation (please do so next time you use a package), it already says to make sure that App\User exists...
It tells you to do:
namespace App;
class User extends Models\User {
//leave this empty
}
For more info, see this github issue or create yourself a new one.

Laravel Model not being found

Hi there I am having trouble using a model within a class there error being shown is Error
Class 'App\Models\RegisteredUsers' not found.
I have made sure that the namespaces match what is being used but I repeatedly get the same error.
Model code
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class RegisteredUsers extends Model
{
//
}
Controller code
<?php
namespace App\Http\Controllers;
use App\Models\RegisteredUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class RegisterUser extends Controller
{
$UserObj = new RegisteredUsers();
}
The directory
App/Http/Controllers/RegisterUser - controller
App/Http/Models/RegisteredUser - model
I created the model and the controller using the command line with PHP artisan.
I have tried the solutions from
laravel model class not found
as well as Model not found in Laravel
and a few laracast questions but i still get the error.
May need to rebuild the classmap
composer dump-autoload
With App\Models namespace in your RegsiteredUser model, the RegisteredUser.php model file must be in the app/Models/RegisteredUser.php directory. Try to move the Models folder outside the Http folder. And from now, you should never put the Models folder in the Http folder again.
Your error is App/Http/Models/RegisteredUser and use App\Models\RegisteredUsers;, did you place your Models in Http?. that is not correct, the Models should be in App root directory, so you are calling the RegisteredUser in the wrong place

Laravel 8, Model factory class not found

so when using the new model factories class introduced in laravel 8.x, ive this weird issue saying that laravel cannot find the factory that corresponds to the model. i get this error
PHP Error: Class 'Database/Factories/BusinessUserFactory' not found in .....
tho ive followed the laravel docs, ive no idea whats going on
Here is the BusinessUser class
<?php
namespace App;
use Database\Factories\BusinessUserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BusinessUser extends Model
{
use HasFactory;
}
and the factory
<?php
namespace Database\Factories;
use App\BusinessUser;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class BusinessUserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = BusinessUser::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'name' => "dsfsf"
];
}
}
any ideas or leads is greatly appreciated.
If you upgraded to 8 from a previous version you are probably missing the autoload directive for the Database\Factories namespace in composer.json:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
You can also remove the classmap part, since it is no longer needed.
Run composer dump after making these changes.
Laravel 8.x Docs - Upgrade Guide - Database - Seeder and Factory Namespace
Apparently you have to respect the folder structure as well. For example, if you have the User Model in the following path: app\Models\Users\User, then the respective factory should be located in database\factories\Users\UserFactory.
I'm in the process of migrating from laravel 7 to 8.
After banging my head against the wall for a while and looking at the source code, I saw that you can optionally override what factory class gets called for a model using the newFactory method on the model.
I also then noticed that it IS in the documentation (https://laravel.com/docs/8.x/database-testing#creating-models) - I just didn't understand what it meant the first time I read it. Now I do.
I solved this by the following:
<?php
namespace My\Fancy\Models;
use Database\Factories\SomeFancyFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class SomeClass extends Model
{
use HasFactory;
/** #return SomeFancyFactory */
protected static function newFactory()
{
return SomeFancyFactory::new();
}
}
After this change, my tests passed as expected.
You need to ensure that the namespace is the same: as shown below: otherwise this will screw you up big time. The name of the factory is the name of the model + Factory
e.g. app\models\User- will match to database/factories/UserFactory
finally ensure you run: composer dumpautoload
In my own case, it happened in a Laravel 8 project ie it wasn't a project I upgraded from Laravel 7. And I noticed this after doing composer update recently.
1: When creating the model, create the factory alongside
php artisan make:model BusinessUser -f // -f creates the factory
2: For your older models comment out use HasFactory; or just create the factory
php artisan make:factory BusinessUserFactory -m
Let's say your model Example is under the App\Example\Models namespace. If you want ALL of your factories under database\factories, then you could define the namespace for your all of factories in your AppServiceProvider:
// ...
use Illuminate\Database\Eloquent\Factories\Factory;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Factory::guessFactoryNamesUsing(function (string $modelName) {
return 'Database\\Factories\\'.class_basename($modelName).'Factory';
});
}
}
And then in your factory, located in database/factories/ExampleFactory.php:
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ExampleFactory extends Factory
{
// ...
}
...as per this twitter comment (I can't take credit for this solution but sharing the fix!):
https://twitter.com/ejunker/status/1306007589940068352/photo/1
I was having this same issue, but for a different reason. If you're using factories in the setUp function of a test, make sure:
You're extending Tests\TestCase (instead of PHPUnit\Framework\TestCase)
The first line of your setUp function should be parent::setUp(); (I was missing this)
Add this to AppServiceProvider::boot() to prevent namespace of model guessing.
Factory::guessFactoryNamesUsing(function (string $modelName) {
return 'Database\\Factories\\' . Arr::last(explode('\\', $modelName)) . 'Factory';
});
It seems like a laravel core issue ! it was caused by the modelName() method located in Illuminate\Database\Eloquent\Factories\Factory.php
Issue was fixed 10 days ago by laravel maintainers in this commit
Fix commit and this release 8.82.0
You can fix the issue by upgrading your laravel version to 8.82.0
Hope this saves you some time. cheers !
May be everything is perfect just run composer dump-autoload. It happened to me.
my problem was related with composer.lock file that was installing laravel v7, solved it with this command
composer update
Use this package if you are upgrading from laravel 7 to 8
composer require laravel/legacy-factories
Today I have got below issue after upgrading my project from Laravel 7 to Laravel 8 and updating it online on server.
Trait 'Illuminate\Database\Eloquent\Factories\HasFactory' not found
Even I have updated composer.json with autoload directive given in answer by #lagbox but it did not resolved the issue for me.
Finally I have updated complete vendors folder online that have resolved my issue.

Laravel - Calling model from controller looks for the wrong file name

I’m assuming this may be some convention I’m not understanding.
I have a model called Ingredient in the main App folder.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ingredient extends Model
{
protected $table = "ingredients";
}
Then I have a controller trying to call that app
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Config;
use App\Ingredient;
class IngredientController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return response()
->json([
'status' => 'ok',
'ingredients' => Ingredient::all()
]);
}
}
Everything seems to be ok. I get a 500 server error though:
include(C:\\Dev\\ScratchApi\\vendor\\composer\/..\/..\/app\/Ingredients.php): failed to open stream: No such file or directory
The file name of the model is Ingredient.php
Do I need to rename my file to Ingredients.php to meet a naming convention? Or why is this trying to call a file name different from the class name I’m telling it to look for?
I think it's because of autoload cache. So, Run following command on your project root directory,
composer dumpautoload
Hope it works.
Add option "-o" when run dump autoload.
composer dump-autoload -o
Try to use this:
composer dump-autoload

Custom class not found in a Laravel app

I've had to try and work with an older package meant for php into my Laravel project.
I've added two custom classes, both are in the same folder "Classes" under the main "app" folder in my Laravel project.
One of these classes is recognized from a generated controller for my Laravel project. My paymentsController has use App\Classes\Quickbooks_Payments; in the top.
However, going to that Classes' file, I hit the following error through a route leading to my controller:
Class 'App\Classes\Quickbooks_Loader' not found
Now this is where this above is referenced in my paymentsController file:
<?php
namespace App\Classes\Quickbooks_Payments;
use App\Classes\Quickbooks_Loader;
/**
* QuickBooks Payments class
*
*/
/**
* Utilities class (for masking and some other misc things)
*/
QuickBooks_Loader::load('/QuickBooks/Utilities.php');
This last line is where the above error is referenced. And I do have both the Quickbooks_Loader.php and the Quickbooks_Payments.php in the same folder. My Quickbooks_Loader.php file starts off as such:
<?php
namespace App\Classes\QuickBooks_Loader;
So I know this is likely because of my inexperience with custom/imported classes. What am I doing wrong and how should I properly "import" these custom classes and have them recognized without any issues?
Change namespace in both classes you've shown to:
namespace App\Classes;
And run composer du
Also, make sure the class looks like this and not like you've shown (I'm not sure about did you cut something or not):
<?php
namespace App\Classes;
use App\Classes\Quickbooks_Loader;
class Quickbooks_Payments
{
public function __construct()
{
dd('It\'s working!');
}
}

Categories