Laravel Factories how to call them from your database seeder file - php

How to call the factorie files from the database seeder I looked at the laravel docs and was trying around whit this code
https://laravel.com/docs/5.7/seeding
factory(App\User::class, 50)->create()->each(function ($user) {
$user->posts()->save(factory(App\Post::class)->make());
});
But it didnt work so mine question is how do i call mine factorie from mine database seeder file so i can execute them from the command line?
databaseseeder
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
$this->call(UserFactory::class);
$this->call(PostFacory::class);
$this->call(ProfileFacory::class);
$this->command->info("Database seeded.");
Eloquent::reguard();
}
}
user factorie
<?php
use Faker\Generator as Faker;
$factory->define(App\User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => bcrypt('password'),
'remember_token' => str_random(10),
];
});

Database seeding is
php artisan db:seed
In the laravel path... also if you have already seeded you have to clean ( sure if do not have inportant data )
php artisan migrate:refresh
Carefully here :)

Related

Can we execute seeder without truncating table or is there any way to achieve this

we are working on a project where I would like to insert one row to database using seeder but when I have executed that seeder it truncates table and insert seeds record. What I want is it should insert a new record only without truncating existing data.
Can anyone help to get this?
This seeder feature is available in mostly all MVC like Laravel and Yii2 that we are using.
use yii\db\Migration;
class m200118_113041_create_table_admin_master extends Migration
{
public function Safeup()
{
$seeder = new \tebazil\yii2seeder\Seeder();
$generator = $seeder->getGeneratorConfigurator();
$faker = $generator->getFakerConfigurator();
$seeder->table('admin_master')->columns([
'email'=>$faker->email,
'password'=>rand(1, 999999),
'created_date'=> date('Y-m-d H:i:s'),
])->rowQuantity(30);
$seeder->refill();
}
public function Safedown()
{
// $this->dropTable('{{%admin_master}}');
}
}
Here above is the example of my migration in Yii2
you can create a new migration file and put insert query in that easily
php artisan make:migration insert_somename_table
than inside migration file
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use DB;
class InsertSomenameTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
DB::('somename')->insert(array('key1' => 'value1', 'key2' => 'value2'));
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
DB::('somename')->where('key1', '=', 'value1')->delete();
}
}
and execute
php artisan migrate
You can do this in two ways
1.Update your seeder
Consider your table name is 'categories' and you already have 12 categories.
You should start your new category id from 13 in the seeder array.
Your seeder look like this
public function run()
{
$data = array(
['id' => 13, 'category' => 'Category1', 'status' => 1],
['id' => 24, 'category' => 'category2', 'status' => 1]
);
DB::table('categories')->insert($data);
}
2. Execute queries
Write one method and execute insert queries

How to seed multiple relationships in Laravel with Faker

I have a database with two columns, brands and shops. Each brand can owe several shops, and I want to seed my database via Fakers using Laravel.
So after setting up the migrations and the relationships in the models
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
/**
* Get the shops for the brand.
*/
public function shops()
{
return $this->hasMany('App\Shop','sh_brand_id');
}
}
And:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function user() {
return $this->belongsTo('App\Brand','sh_brand_id');
}
}
I want to use a Factory to seed the database.
<?php
use Faker\Generator as Faker;
$factory->define(App\Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
];
});
And
use Faker\Generator as Faker;
$factory->define(App\Brand::class, function (Faker $faker) {
return [
'name' => $faker->company,
'logo_url' => $faker->imageUrl(640, 480),
'website' => $faker->url,
'description' => $faker->text(500),
'telephone_number' =>'31'. $faker->randomNumber(8),
'principal_address' => $faker->address,
'email' => $faker->unique()->safeEmail,
];
});
And finally I need to seed the database using those Factories. There are documentation in the website and many examples for do it, but each solution I've found let me generate only one shop for each brand, and I want to generate many shops for each brands.
What is the best way to do this?
Put it directly in your factory. I use a helper method getInstanceOf to pick a random instance of another model.
use Faker\Generator as Faker;
use App\Brand;
use App\Shop;
function getInstanceOf($class, $returnIdOnly = true) {
$instance = $class::inRandomOrder()->first() ?? factory($class)->create();
return $returnIdOnly ? $instance->id : $instance;
}
$factory->define(Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
'sh_brand_id' => getInstanceOf(Brand::class)
];
});
Then when seeding,
factory(App\Brand::class, 10);
factory(App\Shop::class, 50);
I've found this workaround that works for me:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run() {
factory(App\Brand::class, 50)->create()
->each(
function ($br) {
factory(App\Shop::class, 10)->create()
->each(
function($sh) use (&$br) {
$br->shops()->save($sh)->make();
}
);
}
);
}
}

Laravel Seeding missing classes

I am following this tutorial until I need to generate seeds using: php artisan db:seed. It always said that my Article and User class are not found.
I have looking for solution like in:
https://laracasts.com/discuss/channels/lumen/unable-to-run-php-artisan-dbseed-due-to-missing-class (setting up composer.json's auto load paths and composer dump-autoload)
Laravel cannot find class of a package
I have deleting my vendor folder and do composer install again
Also importing the file manually, require_once with relative path to the model from the seeding or root of the projet, but neither works.
I think this should work out-of-the-box but it isn't. What is my problem? And what is my solution?
EDIT 1: Someone requested seeders codes here you are!
Article Seeder
<?php
use Illuminate\Database\Seeder;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
// Let's truncate our existing records to start from scratch.
Article::truncate();
$faker = \Faker\Factory::create();
// And now, let us create a few articles in our database:
for ($i = 0; $i < 50; $i ++) {
Article::create([
'title' => $faker->sentence,
'body' => $faker->paragraph,
]);
}
}
}
User Seeder
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
// Let's clear the user table first
User::truncate();
$faker = \Faker\Factory::create();
// Let's make sure everyone has the same password and
// let's hash it before the loop, or else our seeder
// will be too slow.
$password = Hash::make('toptal');
User::create([
'name' => 'Administrator',
'email' => 'admin#test.com',
'password' => $password,
]);
// And now let's generate a few dozen users for our app:
for ($i = 0; $i < 10; $i ++) {
User:;create([
'name' => $faker->name,
'email' => $faker->email,
'password' => $password,
]);
}
}
}
Database Seeder
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(ArticlesTableSeeder::class);
}
}
First you should import the full class path, i.e.- App\User. Then regenerate the autoload file with- composer dump-autoload
You should either import the models that you've use so you can use just the Model's class name in your code or use the fully qualified name of the Model.
E.g., instead of just User, use App\User.
Use imports if you think you will have many instance where you will use the User class name, to avoid the hassle of typing the fully qualified name.
<?php
...
use App\User;
...
$users = User::all(); // <-- now you can do this.
I followed the same tutorial. Just add a line "use App\Article;" so that your class will find the appropriate class.
Its like including a header file path in c/c++.

Laravel 5.5 Model not found in Seed class

I have been around this problem for so long and cannot solve it... I found several people with (apparently) the same problem as me, but any of the answers helped me.
I have the following "Sector.php" inside "app" folder:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Sector extends Model
{
protected $table = 'sectors';
protected $fillable = ['name'];
protected $guarded = ['id'];
public function services()
{
return $this->belongsToMany('App\Service', 'services_sectors', 'sector_id', 'service_id');
}
public function observations()
{
return $this->belongsToMany('App\Observation', 'observations_sectors', 'sector_id', 'observation_id');
}
}
And the following "DatabaseSeeder.php" inside "database/seeds":
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('sectors')->delete();
Sector::create(['name' => 'Health']);
$this->command->info('Sectors table seeded');
}
}
So, when I access my server I run the command php artisan db:seed but I have the following error:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Sector' not found
I have been trying ./composer update, ./composer dump-autoload -o, changing Sector to App\Sector in the seeder file but the error just changes to Class 'App\Sector' not found.
If I add use App\Sector; to the top of the Seeder file the error is the same.
It seems I tried all the solutions that are online, so maybe I have some configuration done incorrectly? Any suggestions on this?
Try adding use App\Sector; to your seeding file.
Once you have it working, think about separating your seeding files into their separate classes. It is much easier to maintain that way.
Generate Seeder File
First, in terminal, generate a new seed file:
php artisan make:seeder SectorsTableSeeder
Transfer your seeding code into the run method of this new file.
Call seeder files
Then, modify the DatabaseSeeder.php file to run the SectorsTableSeeder class. For example:
public function run()
{
$this->call(SectorsTableSeeder::class);
}
Update
Sorry, I missed that part.
This is what I would try:
$now = date('Y-m-d H:i:s');
public function run()
{
DB::table('sectors')->delete();
DB::table('sectors')->insert([
'name' => 'Health',
'created_at' => $now,
'updated_at' => $now,
]);
$this->command->info('Sectors table seeded');
}

Laravel DB Seeder won't seed in console

Hi I have the following seeder class I am trying to seed. When I run the php artisan db:seed command the only thing that seeds is my previous seeder class I created a few weeks ago. I have no idea what I am missing. I inserted SoftDeletes and Protected fillables as well.
Here is my seeder class:
public function run()
{
DB::table('leave_type')->insert([
[
'leaveType' => 'Vacation Leave'
],
[
'leaveType' => 'Sick Leave'
],
[
'leaveType' => 'Afternoon Off'
],
[
'leaveType' => 'Special Leave'
],
[
'leaveType' => 'Study Leave'
],
]);
}
My model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class LeaveType extends Model
{
protected $fillable = ['leaveType'];
protected $table ="leave_type";
use SoftDeletes;
public $timestamps = true;
}
Converting my comment to answer;
Make sure laravel knows about the new database seeder class you've generated by running this command:
composer dump-auto
Make sure your seeder class is registered in {PROJECT}/database/seeds/DatabaseSeeder.php like this:
$this->call(YourNewSeeder::class);
Then you could refresh the database (rollback all migration, re-run the migration) and run the seeder in one go with this command:
php artisan migrate:refresh --seed
or just run the specific seeder only like this:
php artisan db:seed --class=YourNewSeeder

Categories