Laravel ModelFactory error when seeding - php

My ModelFactory:
<?php
$factory->define(App\Models\Customer::class, function (Faker\Generator $faker) {
return [
'name' => $faker->company,
'email' => $faker->unique()->safeEmail,
'status'=> $faker->numberBetween($min = 0, $max = 2),
'slug'=> $faker->slug,
];
});
Database seeder
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$customers= factory(App\Models\Customer::class, 100)->create();
}
}
When I run
php artisan db:seed
I get the error
[Symfony\Component\Debug\Exception\FatalThrowableError]
Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting '
]'
I've tried everything I can think of, but can't find the problem...
Edit:
I forgot to mention that this was working fine a day earlier and then "broke" as I started to add more ModelFactories (in separate files). I then discarded all my changes (from source control) to be 100% sure I hadn't changed anything. The only other aspect could be that I have something in the .gitignore that may have updated and wasn't rolled back:
/node_modules
/public/storage
/public/hot
/storage/*.key
/.idea
Homestead.json
Homestead.yaml

It seems the problem is this line:
'status'=> $faker->numberBetween($min = 0, $max = 2),
It should be:
'status'=> $faker->numberBetween(0, 2),

Ok, so I found the reason and feel really idiotic about it, but posting it here anyway in case someone follows in my footsteps.
The issue was that there were other ModelFactories in the database/factories folder and it seems that running php artisan db:seed parses those files as well, even though they are not referenced in the DatabaseSeeder class. One of those files had incorrect one-many syntax and that was causing the error.
The only way I realized it was that I ran the factory->create method within php artisan tinker and the error message it threw up referenced this other factory definition.
FWIW, I then used the approach outlined here for my relationships - for the reasons mentioned in the question there...

Related

Laravel Errors in tinker using factory->create() but not when running migration/seed commands in artisan

I am able to successfully run the migration/factory/seeders from the command line using php artisan migrate:fresh --seed
However when I try to manually create a category using tinker, I'm getting errors:
<warning>PHP Warning: Array to string conversion in /Users/[my_name]/Sites/blog/vendor/laravel/framework/src/Illuminate/Support/Str.php on line 99</warning>
TypeError: Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string given, called in /Users/[my_name]/Sites/blog/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 886
And
<warning>PHP Warning: Array to string conversion in /Users/[my_name]/Sites/blog/vendor/laravel/framework/src/Illuminate/Support/Str.php on line 99</warning>
=> App\Models\Category {#4529
name: [
"quaerat",
"voluptatem",
],
slug: "array",
}
Factory code:
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class CategoryFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
$name = $this->faker->words(2,true);
$slug = Str::of($name)->slug('-');
return [
'name' => ucwords($name),
'slug' => $slug
];
}
}
I have two questions:
Why do the two methods (make and create) cause different, albeit related, errors?
Why does tinker get tripped up when the normal migration/seed process works fine?
Please and thank you.
I still don't know why the two errors were different, but it's pedantic.
Thank you to #Rwd! I now know that we need to restart tinker after we change our application code in Laravel.
The string to array error was from a previous version of the code before I figured out to add the second parameter to $this->faker->words() — which is why it worked with php artisan migrate:fresh --seed and with in php artisan tinker \App\Models\Category::factory()->create();

Laravel Seeder Does Not Work

I am using Laravel 5.4.
When I first created a project, I did migration and seeding and all worked fine.
Now I deleted the database and wanted to redo migration and seeding again, migration worked, but seeder does not.
When I entered this command:
php artisan db:seed
the result I got was:
Seeding: xxxTableSeeder
No error, no result was seed. And I should have 4 tables to be seeded but none of it being seeded.
I tried
composer dump-autoload
but not working as well.
DatabaseSeeder.php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(ATableSeeder::class);
$this->call(BTableSeeder::class);
$this->call(CTableSeeder::class);
$this->call(DTableSeeder::class);
}
}
ATableSeeder.php
use Illuminate\Database\Seeder;
class ATableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('A')->insert([
'username' => '',
'firstname' => '',
'lastname' => '',
'email' => '',
'contact' => '',
'password' =>,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
}
Any idea why?
It was the 'timezone' in config/app.php caused the issue. When I first migrated with the default timezone, which is 'UTC', everything works fine. Then I changed the timezone to 'UTC+8', and created_at and updated_at are working fine too. Then here comes the problem. I did migration again with the timezone 'UTC+8' and then stuck at the seeding part.
So now I changed the timezone to 'Asia/Kuala_Lumpur', everything is working perfectly fine!
Thank you guys!
You could try to run php artisan migrate:refresh --seed
Try run this in console:
php artisan dump
Just "dump", without autoload.
Works for me!
Good Luck, I hope be useful!

Laravel 5, Cannot use db:seed (Label DB already defined)

I want to use php artisan db:seed command on my cmd but it said Label 'DB' already defined,
this is my SeederTableAnggota Code:
<?php
use Illuminate\Database\Seeder;
class SeederTableAnggota extends Seeder {
Public function run()
{
DB:table('anggota')->delete();
$anggota= array(
array('id'=>1,'nama'=>'Rizki Amelia Dewi','alamat'=>'Cilengsi'),
array('id'=>2,'nama'=>'Dewi Ayunindita','alamat'=>'Jatinangor'),
array('id'=>3,'nama'=>'Siti Hajar Riska','alamat'=>'Jakarta')
);
DB:table('anggota')->insert('anggota');
}
}
i already use $this->call('SeederTableAnggota') on my DatabaseSeeder.php.
And i already use composer dump-autoload on my cmd too.
So how can i use db:seed and why it said Label 'DB' already defined? thanks for your help and any help will be very useful
It's because you have written DB:table(...) instead of DB::table(...).
You forgot a colon so PHP thought that it is a constant.
Your seeder seems to be too complicated. Do you have a model?
just completing your answer, in my case the problem was because I was typing db::seed when the correct one is db:seed ie I was putting :: when the correct one is : , silly mistake but when you are tired goes unnoticed.

ReflectionException - Class name does not exist in Laravel 5.0

I have a little problem trying to seed my comments table.
I'm 100% sure that I have the Class CommentTableSeeder.php in my /database/seeds directory.
CommentTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class CommentTableSeeder extends Seeder {
public function run()
{
DB::table('comments')->delete();
Comment::create(array(
'author' => 'Chris Sevilleja',
'text' => 'Look I am a test comment.'
));
Comment::create(array(
'author' => 'Nick Cerminara',
'text' => 'This is going to be super crazy.'
));
Comment::create(array(
'author' => 'Holly Lloyd',
'text' => 'I am a master of Laravel and Angular.'
));
}
}
Then when I run : php artisan db:seed
I kept getting
I've also try running composer update and run : php artisan db:seed - still get the same result.
Any hints / help will be much appreciated !
You need to run
composer dump-autoload
to fix this error. What this does, among other things, is refreshes the list of classes available to your application.
In this case, while the class did exist in the right location, it was unavailable in your autoloaded class list, and thus returning a Not Found error.

laravel 'class not found' error on production

Slightly odd one here.
I have Persons and Actions. Persons can have many Actions, while each Action belongs to only one Person. I'm using Chumper's Datatables to display a list of people, including a count of their actions.
Since migrating to a production (forge) server, I'm getting
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Class 'action' not found
when calling the datatable. The error shown
/­vendor/­laravel/­framework/­src/­Illuminate/­Database/­Eloquent/­Model.php:721
public function hasOne($related, $foreignKey = null, $localKey = null)
{
$foreignKey = $foreignKey ?: $this->getForeignKey();
$instance = new $related;
$localKey = $localKey ?: $this->getKeyName();
suggests it's a problem with my hasMany relationship:
# /models/Person.php
class Person extends Eloquent {
public function actions()
{
return $this->hasMany('Action');
}
# /models/Action.php
class Action extends Eloquent {
public function person()
{
return $this->belongsTo('Person', 'person_id');
}
I assume these are fine, however, as it all works locally. Datatables also works fine elsewhere, calling through other items and their related actions with no trouble.
I've tried composer dump-autoload and artisan dump-autoload on the production server, to no avail. The deployment script on forge is below:
git pull origin master
composer install
php artisan migrate --env=production
I can't tell if it's a config issue, a database issue, a code issue or something else entirely. I've been back through the many similar questions but nothing's jumped out. Any help much appreciated.
for who may have the same problem, triple check the casing of your model! I had it wrong, that's why locally on mac was working but not on the server
So I think I'd borked this one myself.
I'd been lazy and left function datatablePersons() in PersonsController.php using an old 'count' method, relying on long-defunct relationships (that caused n+1, so had to be binned), hence it wobbling over an actions class whenever that relationship was called upon.
Datatable functions in other controllers (with a cleaner 'count' method) work fine, so I've just rewritten datatablePersons() to use the same method.
I've not quite got the query right (in eloquent, at least) yet - see this question here: mysql join ON and AND to laravel eloquent - but the class not found error has certainly gone away.
I'm (massively) guessing that the classmap on the local machine hadn't been flushed since whatever was removed was removed, while the production machine is rebuilt every push, hence the disparity...?
Either way, it's no longer an issue.

Categories