Factory/Faker not working in Laravel 5.3 DatabaseSeeder - php

I've moved my code from Laravel 5.2 to 5.3, everything is working fine except when I run my DatabaseSeeder. This was working perfectly in Laravel 5.2, now when I try to run php artisan db:seed in 5.3 I get this error when the Seeder uses Faker:
[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::lists()
Everything seems to be installed correctly.
Code example:
<?php
use App\Models\Gallery;
use App\Models\GalleryImage;
use Illuminate\Database\Seeder;
class GalleryImageTableSeeder extends Seeder
{
public function run()
{
DB::table('gallery_images')->delete();
$faker = Faker\Factory::create();
$gallery = Gallery::lists('id')->All();
foreach(range(1, 98) as $index) {
GalleryImage::create([
'page_id' => null,
'gallery_id' => $faker->randomElement($gallery),
'alt' => 'Image description',
'large' => '201508183828fh5ntu80ub-or.jpg',
'medium' => '201508183828fh5ntu80ub-lg.jpg',
'thumbnail' => '201508183828fh5ntu80ub-th.jpg',
'order' => 1,
'cover' => false,
'visibility' => 'visible',
]);
}
}
}

At last i found it out mysql. Need to change list to pluck
Example:
$gallery = Gallery::pluck('id')->All();

Related

Unable to locate factory with name on production?

I create a factory of a model inside an artisan command:
public function handle()
{
if (!$this->isDevelopment()) {
$this->errorMessageSwitchEnvToDev();
return;
}
$userId = $this->ask('Please specifiy user_id you want to add the payouts to.',2148);
$numberOfPayouts = $this->ask('How many payouts you want to generate?', 10);
factory(\App\Payout::class, $numberOfPayouts)->create([
'user_id' => $userId,
]);
}
The artisan works on my local desktop, but it does not work after deployment on my test server.
I get the following error message:
InvalidArgumentException : Unable to locate factory with name [100] [App\Payout].
at /www/htdocs/w0146a6f/dev/dev4.partner.healyworld.net/releases/20201014150056/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:269
265| */
266| protected function getRawAttributes(array $attributes = [])
267| {
268| if (! isset($this->definitions[$this->class][$this->name])) {
> 269| throw new InvalidArgumentException("Unable to locate factory with name [{$this->name}] [{$this->class}].");
270| }
271|
272| $definition = call_user_func(
273| $this->definitions[$this->class][$this->name],
Exception trace:
1 Illuminate\Database\Eloquent\FactoryBuilder::getRawAttributes([])
/www/htdocs/w0146a6f/dev/dev4.partner.healyworld.net/releases/20201014150056/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:292
2 Illuminate\Database\Eloquent\FactoryBuilder::Illuminate\Database\Eloquent\{closure}()
/www/htdocs/w0146a6f/dev/dev4.partner.healyworld.net/releases/20201014150056/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php:122
I do the deployment with envoyer.
My factory is defined in database/factories/PayoutFactory.php
<?php
$factory->define(\App\Payout::class, function (Faker\Generator $faker) {
return [
'user_id' => function () {
return factory(App\User::class)->create()->id;
},
'amount' => $faker->randomFloat(2),
'req_amount' => 0,
'tax_amount' => 0,
'withheld' => 0,
'vat_rate' => $faker->randomNumber(2),
'released_amount' => $faker->randomFloat(2),
'released_amount_local_currency' => $faker->randomFloat(2),
'status' => 'released',
'flag' => 0,
'created_at' => $faker->dateTimeBetween('-6 months', 'now'),
];
});
However, it won't work on production. I already cleared the cache, the routes and called composer dump-autoload, but it still failes with the same issue.
Any suggestions?
I also read all answers of Laravel 5.2: Unable to locate factory with name [default] but none of them worked.
Notice this:
Unable to locate factory with name [100]
It looks like factory() is willing to use states instead of quantity. In this case it's looking for a factory state called (string) "100" instead of (int) 100
Cast your amount variable to be an integer
$numberOfPayouts = (int) $this->ask('How many payouts you want to generate?', 10);
Alternatively, try using ->times($amount) method to be more explicit.

Adding a new custom Customer attribute when updating a module

I'm having troubles at creating new customer attribute when upgrading one of my modules.
I've created the UpgradeData.php file under /app/code/vendor/modulename/Setup/UpgradeData.php with the current code:
namespace Ucs\CustomerAttribute\Setup;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
class UpgradeData implements UpgradeDataInterface{
private $customerSetupFactory;
public function __construct(
CustomerSetupFactory $customerSetupFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
}
/**
* {#inheritdoc}
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context){
$setup->startSetup();
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
if (version_compare($context->getVersion(), '1.0.6') < 0) {
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'nome_azienda', [
'type' => 'varchar',
'label' => 'Nome azienda',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'nome_azienda')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]]);
$attribute->save();
$customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'codice_univoco', [
'type' => 'varchar',
'label' => 'Codice Univoco',
'input' => 'text',
'source' => '',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => ''
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'codice_univoco')
->addData(['used_in_forms' => [
'adminhtml_customer',
'adminhtml_checkout',
'customer_account_create',
'customer_account_edit'
]]);
$attribute->save();
}
}
}
in short, it needs to create 2 new text (varchar) attributes. My module.xml has
setup_version="1.0.5" schema_version="1.0.5" so it should enter the version_compare condition and create the attribute, but, after running php bin/magento setup:upgrade it doesn't work. If i check in the setup_module table, the setup_version and schema_version change correctly with the version in the module.xml. It looks like for some reason the UpgradeData.php does not get executed at all.
In Ucs\CustomerAttribute\etc\module.xml
change version to 1.0.6
then replace
if (version_compare($context->getVersion(), '1.0.6') < 0) {
with
if (version_compare($context->getVersion(), '1.0.6', '<')) {
Edit: Just to be sure.. by
I've created the UpgradeData.php file under
/app/code/vendor/modulename/Setup/UpgradeData.php
You mean app/code/Ucs/CustomerAttribute/Setup/UpgradeData.php ?
Edit2:
I assumed Your agency is called Ucs. That's why I've asked about it, beacuse that's what suggest Your module namespace.
This is not recomended practice but for purpose of installator verification, change namespace to:
namespace vendor\modulename\Setup;
What I recomend is:
Create a new module or find app/code/[YOURCOMPANYNAME]/Customer - try to corespond Magento native modules. This way You can easier manage code, design and Magento doesn't need to load separated module for each functionallity.
In UpgradeData.php try to call separate function for each version.
Like:
if (version_compare($context->getVersion(), '1.0.1', '<')) {
$this->addCustomerMyAttribute();
}
$setup->endSetup();
and then below
private function addCustomerMyAttribute($setup){
// Your code goes here
}
If it's first version of Customer module in app/code/[YOURCOMPANYNAME] remember to create InstallData.php insted of UpgradeData.php (in that case no need to check version).
After bin/magento setup:upgrade check eav_attribute table for new attribute.
If it's there remember to bin/magento indexer:reindex so it goes to flat table. If it's not there. Put ```die(var_dump('I'm running'); at the beginning of upgrade function.

Phinx seeders work in console but not work in unit test

I have a project made with slim, Eloquent and Phinx and I am integrating PHPunit.
Everything works correctly except the new test that I need to perform an information seeder before executing the test.
The seed
<?php
use Phinx\Seed\AbstractSeed;
class Permissions extends AbstractSeed
{
/**
* Run Method.
*
* Write your database seeder using this method.
*
* More information on writing seeders is available here:
* http://docs.phinx.org/en/latest/seeding.html
*/
public function run()
{
$data = [
[
'id' => '1',
'level' => 'admin',
'created_at' => date('Y-m-d H:i:s'),
],
];
$level = $this->table('users_levels');
$level->insert($data)
->save();
$data = [
[
'users_level_id' => '1',
'method' => 'GET',
'url' => '/api/events/{date:\d{4}-\d{1,2}-\d{1,2}}',
'created_at' => date('Y-m-d H:i:s'),
],
[
'users_level_id' => '1',
'method' => 'POST',
'url' => '/api/event',
'created_at' => date('Y-m-d H:i:s'),
],
];
$urls = $this->table('level_urls');
$urls->insert($data)
->save();
}
}
I run it from the console works perfectly,
C:\xampp\htdocs\CirceApi> .\vendor\bin\phinx seed:run
Phinx by CakePHP - https://phinx.org. 0.8.1
using config file .\phinx.php
using config parser php
using migration paths
- C:\xampp\htdocs\CirceApi\database\migrations
using seed paths
- C:\xampp\htdocs\CirceApi\database\seeds
warning no environment specified, defaulting to: development
using database circe
== Permissions: seeding
== Permissions: seeded 0.1773s
but when I launch it in the following way for the tests
use Phinx\Console\PhinxApplication;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\NullOutput;
protected function runMigration()
{
$app = new PhinxApplication();
$app->setAutoExit(false);
$app->doRun(new StringInput("migrate"), new NullOutput());
$app->doRun(new StringInput("seed:run"), new NullOutput());
}
it returns the following error.
14) Tests\Profile\ProfileTest::it_returns_404_status_code_when_profile_is_not_found
PDOException: SQLSTATE[HY000]: General error: 1 table users_levels has no column named level
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Db\Adapter\PdoAdapter.php:215
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Db\Adapter\AdapterWrapper.php:191
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Db\Adapter\TimedOutputAdapter.php:125
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Db\Table.php:667
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Db\Table.php:610
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Db\Table.php:697
C:\xampp\htdocs\CirceApi\database\seeds\Permissions.php:29
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Migration\Manager\Environment.php:156
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Migration\Manager.php:403
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Migration\Manager.php:536
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Console\Command\SeedRun.php:110
C:\xampp\htdocs\CirceApi\vendor\symfony\console\Command\Command.php:255
C:\xampp\htdocs\CirceApi\vendor\symfony\console\Application.php:901
C:\xampp\htdocs\CirceApi\vendor\symfony\console\Application.php:262
C:\xampp\htdocs\CirceApi\vendor\robmorgan\phinx\src\Phinx\Console\PhinxApplication.php:83
C:\xampp\htdocs\CirceApi\tests\UseDatabaseTrait.php:19
C:\xampp\htdocs\CirceApi\tests\BaseTestCase.php:44
ERRORS!
Tests: 17, Assertions: 7, Errors: 14.
Thanks for the help.
Try this:
use Phinx\Console\Command\SeedRun;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
$phinxApplication = new Application();
$phinxApplication->add(new SeedRun());
$phinxSeedRunCommand = $phinxApplication->find('seed:run');
$phinxCommandTester = new CommandTester($phinxSeedRunCommand);
$phinxCommandTester->execute(['command' => $phinxSeedRunCommand->getName()]);
$phinxDisplay = $phinxCommandTester->getDisplay();
$phinxStatusCode = $phinxCommandTester->getStatusCode();
if ($phinxStatusCode > 0) {
throw new RuntimeException('Seed:run failed');
}

Database Seeder cannot find class with Laravel 5.2

When running php artisan migrate --seed, this error appears:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'CreateCharactersTable' not found.
Here is that that class:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class CharacterSeeder extends Seeder
{
public function run()
{
DB::table('characters')->delete();
DB::table('characters')->insert([
'user_id' => 999,
'name' => 'Susan Strong',
'race' => 'orc',
'class' => 'assassin',
'image_location' => null,
'combat_level' => '0',
'base_str' => 6,
'base_int' => 4,
'base_apt' => 5,
'mod_str' => 9,
'mod_int' => 5,
'mod_apt' => 7,
'xp_str' => 1,
'xp_int' => 2,
'xp_apt' => 1,
'is_bot' => 1,
'created_at'=> '2017-04-02 17:53:02',
'updated_at'=> '2017-04-02 17:53:02'
]);
DB::table('characters')->insert([
'user_id' => 4,
'name' => 'Chale',
'race' => 'elf',
'class' => 'scholar',
'image_location' => null,
'combat_level' => '0',
'base_str' => 3,
'base_int' => 7,
'base_apt' => 5,
'mod_str' => 6,
'mod_int' => 10,
'mod_apt' => 6,
'xp_str' => 1,
'xp_int' => 2,
'xp_apt' => 1,
'is_bot' => 1,
'created_at'=> '2017-04-02 17:53:02',
'updated_at'=> '2017-04-02 17:53:
}
}
?>
and the seeder:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Database\Seeds\CharacterSeeder;
use Database\Seeds\ClassesTableSeeder;
use Database\Seeds\RacesTableSeeder;
use Database\Seeds\UserTableSeeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(CharacterSeeder::class);
$this->call(RacesTableSeeder::class);
$this->call(ClassesTableSeeder::class);
}
}
Running composer dumpautoload passes but does not remove the error. When it was only two seeders, User and Character, it ran well. Despite looking over the new seeders again and again, I cannot determine the error involved.
Any suggestions to get the seeder to run?
Thank you.
If you manually added the seeder files you should first run composer dump-autoload. This will regenerate the autoload_classmap.php file for you, see Composer Dump-Autoload for more info.
You've imported all your seeders from a namespace, but they aren't in a namespace.
use Database\Seeds\CharacterSeeder;
use Database\Seeds\ClassesTableSeeder;
use Database\Seeds\RacesTableSeeder;
use Database\Seeds\UserTableSeeder;
Just remove those lines and you should be good to go.
Class 'CreateCharactersTable' should is Migration. You need check this migration file or class exists.
if you only use seeder . you can exec
php artisan db:seed

Codeigniter an migration not working with wamp

I am following a tutorial and I have check the source code with my code to make sure there are no errors but I am unable to get codeigniter to create update or retrieve any records from my wamp sever(ver 2.4) when I enter public_html/admin/migration in the task bar codeigniter returns a message saying "Migration worked!" which is the result that is expected when codeigniter has updated the records but no changes are made to the database this is the code used in the controller
<?php
class Migration extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
$this->load->library('migration');
if (! $this->migration->current()) {
show_error($this->migration->error_string());
}
else {
echo 'Migration worked!';
}
}
}
I have set the autoload libraries as follows $autoload['libraries'] = array('database');
is there something I am missing
here is my migration library file called '001_create_users.php'
<?php
class Migration_Create_users extends CI_Migration {
public function up()
{
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 11,
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'email' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
'password' => array(
'type' => 'VARCHAR',
'constraint' => '128',
),
'name' => array(
'type' => 'VARCHAR',
'constraint' => '100',
),
));
$this->dbforge->create_table('users');
}
public function down()
{
$this->dbforge->drop_table('users');
}
}
Not sure if you are referring to the tutorial by Free Courses on youtube about cms buildout in codeigniter.
The way I fixed the issue (after a few hours) was debugging down to the environment setup.
Replace everything in your index function of the migration controller with var_dump($this->db) and see what it returns for your username/password/hostname/database, etc. If they are not what you expected per your database library setup, then your environment is not set properly in the index.php file.
I had to fix my case statement, had an extra / or \ can not remember which one, so the switch statement was forcing it to use the production environment configuration, which were not set.
add primary key before create table
$this->dbforge->add_key('id');

Categories