Laravel 5.6 - Seeder Class not found - php

I'm trying to populate a Laravel 5.6 project DB - following the offial docs - without success. php artisan db:seed throws this exception:
Symfony\Component\Debug\Exception\FatalThrowableError : Class 'App\Item' not found
at /Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:217
Exception trace:
1 Illuminate\Database\Eloquent\FactoryBuilder::make([])
/Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:167
2 Illuminate\Database\Eloquent\FactoryBuilder::create()
/Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/database/seeds/ItemTableSeeder.php:14
I already tried most of the common suggestions provided from the community, like this one, as well as:
Trying with composer self-update + composer dump-autoload;
On my composer.json the autoload property is set as is:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
(Tried to put classmap in autoload-dev too).
Here's the situation:
ItemFactory.php
<?php
use Faker\Generator as Faker;
// Definizione dati test
$factory->define(App\Item::class, function (Faker $faker) {
return [ ...]
}
ItemTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ItemTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Item::class, 25)->create();
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(ItemTableSeeder::class);
}
}
At last, I tried to put dependencies directly in sources too:
use App\Item;
use Illuminate\Database\Seeder;
by removing the App\ prefix and leave only Item::class in the argument:
factory(Item::class, 25)->create();
All these tries didn't helped, so I'm actually stuck.
If anyone could show me the way, it should be really appreciated.
Thanks in advance to all.
UPDATE
#kerbholz & #h-h: There was a mistyped trait in ItemTableSeeder.php, thanks for both your suggestion. Yes, in first place I implemented an Item.php model like this:
<?php
// Definizione Namespace
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Classe Item
*/
class Item extends Model
{
use SoftDeletes;
// Dichiarazione Proprietà
protected $table = 'item';
protected $dateformat = 'Y-m-d';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'data_acquisto',
'labeled',
'estensione_garanzia',
'stato',
'data_dismissione',
'note'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'codice',
'serial',
'componente_id',
'tipologia_id',
'condizione_id',
'locazione_id',
'fornitore_id',
'parent_id'
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'data_acquisto',
'data_dismissione',
'deleted_at'
];
/**
* All of the relationships to be touched.
*
* #var array
*/
protected $touches = [
'componenti',
'condizioni',
'fornitori',
'locazioni',
'tipologie'
];
/**
* Scope query item figli
* Getter
* #param array $query Query
* #return array Query
*/
public function scopeFigli($query)
{
return $query->where('parent_id', '!=', null);
}
/**
* Componenti Correlati
* Getter
* #return object Componenti
*/
public function componenti()
{
// Definizione relazione
return $this->belongsTo('App\Componente');
}
/**
* Condizioni Correlate
* Getter
* #return object Condizioni
*/
public function condizioni()
{
// Definizione relazione
return $this->belongsTo('App\Condizione');
}
/**
* Fornitori Correlati
* Getter
* #return object Fornitori
*/
public function fornitori()
{
// Definizione relazione
return $this->belongsTo('App\Fornitore');
}
/**
* Locazioni Correlate
* Getter
* #return object Locazioni
*/
public function locazioni()
{
// Definizione relazione
return $this->belongsTo('App\Locazione');
}
/**
* Tipologie Correlate
* Getter
* #return object Tipologie
*/
public function tipologie()
{
// Definizione relazione
return $this->belongsTo('App\Tipologia');
}
}
Meanwhile I continued to implement others. Now, after correcting the mistype and run again twice a composer dump-autoload seeding started. It populated some tables, but after that thrown a new exception. Here's an extract from last try:
Seeding: ItemTableSeeder
ErrorException : Illegal offset type
at /Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:257
253| * #throws \InvalidArgumentException
254| */
255| protected function getRawAttributes(array $attributes = [])
256| {
257| if (! isset($this->definitions[$this->class][$this->name])) {
#h-h: In this case, I tried to put backslash before "App": \App\Item::class with no success. Dunno if it's related to some faker misconfiguration...

Found it.
Inside ItemFactory.php I put a stupid $this as factory parameter, in a relation creation:
$factory->define(App\Item::class, function (Faker $faker) {
[...]
'parent_id' => function() {
return factory($this)->create()->id;
}
}
By changing the return sentence in this way:
return factory(App\Item::class)->create()->id;
the issue seems to be solved.
Thanks everyone for the assistance.

You need to either import the Item class like so:
use App\Item;
which means you can do this:
factory(Item::class, 25)->create();
--
Or put a \ before hand like so:
factory(\App\Item::class, 25)->create();
--
Also make sure your Item class has this at the top:
namespace App;

Normally Seeder Class Not Found error occurs, when we have different git branches and we checkout to new branch.
php artisan db:seed --class=StockBranchFileSeeder
Exception: For Target class [StockBranchFileSeeder] does not exist.
Seeder Exception
So I resolved this issue simply run below code in project root;
composer dump-autoload
now Seeder has been successfully executed.

Related

Laravel 8 factory not found despite dumping composer autoloader

I'm creating factories in my Laravel 8 project, I've used them before so am quite familiar with their set up.
In my project, I'm having trouble getting Laravel to pick up my factories and cannot figure out why, the error I'm getting is that my factory class can't be found, I've tried composer dump-autoload and also have tried various cache clearing commands with no result.
What am I missing?
My database/factories/BrandFactory is:
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Carbon\Carbon;
class BrandFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Brand::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
$todo = $this->faker->unique()->company();
$slug = Str::slug($brand);
return [
'user_id' => User::all()->random()->id,
'brand' => $brand,
'slug' => $slug,
'url' => $this->faker->domain(),
'created_at' => Carbon::now()->subDays(rand(1, 14))
];
}
}
I have HasFactory on my model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Brand extends Model
{
use HasFactory, SoftDeletes;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'brands';
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'brand',
'url'
];
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = [
'form'
];
/**
* Get the form associated with the user.
*/
public function form()
{
return $this->hasOne(Form::class);
}
/**
* Get the brand that owns the comment.
*/
public function brand()
{
return $this->belongsTo(User::class);
}
}
Which is called from my seeder:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Brand;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
Brand::factory(3)->create();
}
}
Also, since this is a Laravel 8 project, autoloader is configured correctly to:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
}
Your code look fine, anyway, you can tell your model to find it's own factory using newFactory method:
In your model:
protected static function newFactory()
{
return Database\Factories\BrandFactory::new();
}

ServiceProvider binded class not found

Case (L5.4)
Currently trying to write an api wrapper using the package development Laravel offers.
I got a ServiceProvider which binds the model (Niki::class)
class NikiServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/config/niki.php' => config_path('niki.php'),
]);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('niki', function () {
return new Niki;
});
}
}
A Facade which registers the name of the component
class Facade extends \Illuminate\Support\Facades\Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
public static function getFacadeAccessor()
{
return 'niki';
}
}
And a model
class Niki extends Model
{
/**
* Config
*
* #var array
*/
public function __construct()
{
$this->config = config('niki')['api_key'];
}
public static function getHouses()
{
$response = $this->config;
return $response;
}
}
Above files are located in packages/prsc/niki/src and are being loaded using the psr-4 autoloading:
"psr-4": {
"App\\": "app/",
"PRSC\\Niki\\": "packages/prsc/niki/src/"
},
Error
So now my problem, the bind in the ServiceProvider returns a FatalError because of the file not being found.
FatalThrowableError in NikiServiceProvider.php line 37: Class
'PRSC\Niki' not found
I think it's just a namespace problem. I'm not sure I have all the clue about your namespaces, but here is something that should work (if I did not misunderstood):
Replace:
return new Niki;
By:
return new \PRSC\Niki\Niki;
If it does not work, please add your namespaces in each code snippet you pasted.

Laravel 5.3 Routes are not working - boilerpate repo

I am using latest repo of laravelboilerplate i got this error on server. but it works fine on homestead.
I try to user clear:cache but its the same.
UnexpectedValueException in Route.php line 646:
Invalid route action: [App\Http\Controllers\Backend\Takeaway\addOnCategory\AddOnCategoryTableController]
and here is the code in controller
<code>
namespace App\Http\Controllers\Backend\Takeaway\AddOnCategory;
use App\Http\Controllers\Controller;
use App\Repositories\Backend\Takeaway\AddOnCategory\AddOnCategoryRepository;
use Yajra\Datatables\Facades\Datatables;
use App\Http\Requests\Request;
/**
* Class UserTableController
*/
class AddOnCategoryTableController extends Controller
{
/**
* #var UserRepository
*/
protected $addOnCategory;
/**
* #param UserRepository $users
*/
public function __construct(AddOnCategoryRepository $addOnCategory)
{
$this->addOnCategory = $addOnCategory;
}
/**
* #param ManageUserRequest $request
* #return mixed
*/
public function __invoke() {
return Datatables::of($this->addOnCategory->getForDataTable())
->addColumn('actions', function($addOnCategory) {
return $addOnCategory->action_buttons;
})
->make(true);
}
}
and here is the code in route
<code>
Route::group([
'prefix' => 'takeaway',
'as' => 'takeaway.',
'namespace' => 'Takeaway\addOnCategory',
], function() {
/**
* Settings Specific Functionality
*/
/**
* User CRUD
*/
Route::resource('/addOnCategory', 'AddOnCategoryController');
Route::get('addOnCat/get', 'AddOnCategoryTableController')->name('addOnCategory.get');
});
You need to provide the name of your method with AddOnCategoryTableController
Just try like this
Route::get('addOnCat/get', 'AddOnCategoryTableController#__invoke')->name('addOnCategory.get');

How do I solve "Target [Interface] is not instantiable" in Laravel 4?

My error message:
Illuminate \ Container \ BindingResolutionException
Target [Project\Backend\Service\Validation\ValidableInterface] is not instantiable.
I understand that interfaces and abstract classes are not instantiable so I know that Laravel should not be trying to instantiate my interface. Yet somehow it's trying to and I suspect this may be a binding issue...even though I believe I have bound it correctly and have registered it as a service provider.
I should mention that I have taken this example out of Chris Fidao's "Implementing Laravel" and it's almost identical!
This is the first couple of lines of my form class:
namespace Project\Backend\Service\Form\Job;
use Project\Backend\Service\Validation\ValidableInterface;
use Project\Backend\Repo\Job\JobInterface;
class JobForm {
/**
* Form Data
*
* #var array
*/
protected $data;
/**
* Validator
*
* #var \Project\Backend\Form\Service\ValidableInterface
*/
protected $validator;
/**
* Job repository
*
* #var \Project\Backend\Repo\Job\JobInterface
*/
protected $job;
public function __construct(ValidableInterface $validator, JobInterface $job)
{
$this->validator = $validator;
$this->job = $job;
}
This is the first few lines of my validator class:
namespace Project\Backend\Service\Form\Job;
use Project\Backend\Service\Validation\AbstractLaravelValidator;
class JobFormValidator extends AbstractLaravelValidator {
// Includes some validation rules
This is the abstract validator:
namespace Project\Backend\Service\Validation;
use Illuminate\Validation\Factory;
abstract class AbstractLaravelValidator implements ValidableInterface {
/**
* Validator
*
* #var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Validation data key => value array
*
* #var Array
*/
protected $data = array();
/**
* Validation errors
*
* #var Array
*/
protected $errors = array();
/**
* Validation rules
*
* #var Array
*/
protected $rules = array();
/**
* Custom validation messages
*
* #var Array
*/
protected $messages = array();
public function __construct(Factory $validator)
{
$this->validator = $validator;
}
This is the code where I bind it all to the app:
namespace Project\Backend\Service\Validation;
use Illuminate\Support\ServiceProvider;
use Project\Backend\Service\Form\Job\JobFormValidator;
class ValidationServiceProvider extends ServiceProvider {
public function register()
{
$app = $this->app;
$app->bind('Project\Backend\Service\Form\Job\JobFormValidator', function($app)
{
return new JobFormValidator($app['validator']);
});
}
}
This is then registered in app/config/app.php:
.....
'Project\Backend\Service\Validation\ValidationServiceProvider',
....
Finally these are the first few lines of my controller:
use Project\Backend\Repo\Job\JobInterface;
use Project\Backend\Service\Form\Job\JobForm;
class JobController extends \BaseController {
protected $jobform;
function __construct(JobInterface $job, JobForm $jobform)
{
$this->job = $job;
$this->jobform = $jobform;
}
You need to tell Laravel which instance it should use for a certain interface when injecting it into the constructor via type hinting.
You do this using the bind() method (in your service provider for example)
$app->bind('JobInterface', 'Job'); // Job being the class you want to be used
I highly recommend you watch the video here where Taylor Otwell, the creator of Laravel, explains this and some other things.
First you need to bind using
/app/Providers/AppServiceProvider.php
<?php namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
$this->app->bind('JobInterface', 'Job');
}
}
Once you complete this change
Run composer update

User model error after Laravel update (Class User contains 3 abstract method)

After I update my laravel using composer update, I got this
"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Class User contains 3 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\\Auth\\UserInterface::setRememberToken, Illuminate\\Auth\\UserInterface::getRememberTokenName, Illuminate\\Auth\\Reminders\\RemindableInterface::getReminderEmail)",
"file":"D:\app\\models\\User.php",
"line":54
error when authenticating.
This error happened because of the latest commit.
You can check the upgrade documentation here, to fix this issue.
As stated, add the following to your User.php model class:
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
This is what worked for me by adding the below to app/User
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
Example app/User
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}

Categories