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!
Related
After connecting to database, I want to programmatically run migration and seeder once the project detects that the database doesn't have any tables.
I think what I should do is inject the code below somewhere, but I don't know what file I should edit.
if (!Schema::hasTable('users')) {
$init_met = ini_get('max_execution_time');
set_time_limit(300);
Artisan::call('migrate:fresh');
Artisan::call('db:seed');
set_time_limit($init_met);
}
Or, is there an alternative way to do this instead of injecting the code?
Thanks in advance.
i'd suggest you to look at composer scripts section - there are a lot of events that could be used as trigger for your code. for example post-autoload-dump event fired after composer dumpautoload which is fired in most common calls like install, update or by itself. the benefit of using composer events is that you don't need to check for existing tables on each request.
the most easy way to achieve this is to create custom artisan command
php artisan make:command PrepareEmptyDatabase
then in app\Console\Commands\PrepareEmptyDatabase.php
<?php
namespace App\Console\Commands;
use Exception;
use App\Http\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Artisan;
class PrepareEmptyDatabase extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'db:prepare-empty';
/**
* The console command description.
*
* #var string
*/
protected $description = 'check for users table and run migrations and seed if has not';
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
// don't forget to remove this if database user
// don't have access to dba tables
if (Schema::hasTable('users')) {
return Command::SUCCESS;
}
/*
// if your user doesn't have permission to access to dba tables
// you can simply try to do any request to users table
$needActions = false;
try {
User::first();
} catch (Exception $ex) {
$needActions = true;
}
if (!$needActions) {
return Command::SUCCESS;
}
*/
$init_met = ini_get('max_execution_time');
set_time_limit(300);
Artisan::call('migrate:fresh');
Artisan::call('db:seed');
set_time_limit($init_met);
return Command::SUCCESS;
}
}
and the last step is tie this command with composer event, so in composer.json
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover",
"#php artisan db:prepare-empty"
]
},
now any time you install/update composer dependencies or just run composer dumpatoload application will run your custom command. or you can stick with any of provided in composer docs event on your taste
about running the same code after npm run dev
i'm not quite sure about place to search, guess its about webpack events, but your question tagged with laravel so i assume you're using laravel-mix and there are event hooks
quick googling says that nodejs can run bash scripts using nodejs child process
// webpack.mix.js
const exec = require('child_process')
// or import exec from 'child_process'
mix
.js('resources/assets/js/app.js', 'public/js')
// other configs
.after(() => {
exec.execSync('php artisan db:prepare-empty')
})
pay attention that this code will run on any mix even including npm run prod for example and i don't actually understand why do you need it in frontend build event (if only for testing purpose and even then its questionable)
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();
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...
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.
I have installed laravel 5 and looking for scaffolding but when i run this command
php artisan make:scaffold Tweet --schema="title:string:default('Tweet #1'), body:text"
it is giving exception "The "--no-migration" option does not exist".
I have checked it with php artisan migrate --help command and the option does not exists.
Can anybody help me please?
Thanks.
The laralib/l5scaffold extension does not have a --no-migration option. So you cannot prevent creating the migration files via command.
Currently I don't see any suitable way to achieve the desired behaviour. Just delete the migration files afterwards.
Or implement the feature yourself and create a pull request to the repository. You will probably only need to change src/Commands/ScaffoldMakeCommand.php. Here are some hints:
public function fire()
{
// ...
// Generate files
if (!$this->option('no-migration')) {
$this->makeMigration();
}
$this->makeSeed();
// ...
}
protected function getOptions()
{
return [
['schema', 's', InputOption::VALUE_REQUIRED, 'Schema ...', null],
['form', 'f', InputOption::VALUE_OPTIONAL, 'Use ...'],
['no-migration', 'm', InputOption::VALUE_OPTIONAL, 'Don\'t create migration files.']
];
}