I've created migrations and migrated them to the database. Now ready to create seeders, but php artisan db:seed gives this error Class 'Seeder' not found.
How do I create a seeder class and where is it stored?
I'm following this tutorial https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel and am at the point where we 'Seeding a Database with Relationships'.
Here is my DatabaseSeeder.php
// app/database/seeds/DatabaseSeeder.php
<?php
use App\Bear;
use App\Tree;
use App\Fish;
use App\Picnic;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
// call our class and run our seeds
$this->call('BearAppSeeder');
$this->command->info('Bear app seeds finished.'); // show information in the command line after everything is run
}
}
// our own seeder class
// usually this would be its own file
class BearAppSeeder extends Seeder
{
public function run()
{
// clear our database ------------------------------------------
DB::table('bears')->delete();
DB::table('fish')->delete();
DB::table('picnics')->delete();
DB::table('trees')->delete();
DB::table('bears_picnics')->delete();
// seed our bears table -----------------------
// we'll create three different bears
// bear 1 is named Lawly. She is extremely dangerous. Especially when hungry.
$bearLawly = Bear::create(array(
'name' => 'Lawly',
'type' => 'Grizzly',
'danger_level' => 8
));
// bear 2 is named Cerms. He has a loud growl but is pretty much harmless.
$bearCerms = Bear::create(array(
'name' => 'Cerms',
'type' => 'Black',
'danger_level' => 4
));
// bear 3 is named Adobot. He is a polar bear. He drinks vodka.
$bearAdobot = Bear::create(array(
'name' => 'Adobot',
'type' => 'Polar',
'danger_level' => 3
));
$this->command->info('The bears are alive!');
// seed our fish table ------------------------
// our fish wont have names... because theyre going to be eaten
// we will use the variables we used to create the bears to get their id
Fish::create(array(
'weight' => 5,
'bear_id' => $bearLawly->id
));
Fish::create(array(
'weight' => 12,
'bear_id' => $bearCerms->id
));
Fish::create(array(
'weight' => 4,
'bear_id' => $bearAdobot->id
));
$this->command->info('They are eating fish!');
// seed our trees table ---------------------
Tree::create(array(
'type' => 'Redwood',
'age' => 500,
'bear_id' => $bearLawly->id
));
Tree::create(array(
'type' => 'Oak',
'age' => 400,
'bear_id' => $bearLawly->id
));
$this->command->info('Climb bears! Be free!');
// seed our picnics table ---------------------
// we will create one picnic and apply all bears to this one picnic
$picnicYellowstone = Picnic::create(array(
'name' => 'Yellowstone',
'taste_level' => 6
));
$picnicGrandCanyon = Picnic::create(array(
'name' => 'Grand Canyon',
'taste_level' => 5
));
// link our bears to picnics ---------------------
// for our purposes we'll just add all bears to both picnics for our many to many relationship
$bearLawly->picnics()->attach($picnicYellowstone->id);
$bearLawly->picnics()->attach($picnicGrandCanyon->id);
$bearCerms->picnics()->attach($picnicYellowstone->id);
$bearCerms->picnics()->attach($picnicGrandCanyon->id);
$bearAdobot->picnics()->attach($picnicYellowstone->id);
$bearAdobot->picnics()->attach($picnicGrandCanyon->id);
$this->command->info('They are terrorizing picnics!');
}
}
After I got the error I tried to add a model called Seeder.php and added the following:
// app/models/seeder.php
<?php
class Seeder extends Seeder
{
protected $fillable = [];
protected $table = 'bear';
}
I've tried all the answers found on here, also composer dump-autoload but no joy.
You need to make sure to import the Illuminate Seeder class which your class extends
use App\Bear;
use App\Tree;
use App\Fish;
use App\Picnic;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
// Rest of code
At the top of your class
Related
I've made the following seed to fill in a table
<?php
use Illuminate\Database\Seeder;
use TCG\Voyager\Models\Menu;
use TCG\Voyager\Models\MenuItem;
class AddChatMenuSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$menu = Menu::where('name', 'admin')->firstOrFail();
$client_menu = Menu::where('name', 'menu')->firstOrFail();
// Add a tab of our chat
$user = MenuItem::firstOrNew([
'menu_id' => $client_menu->id,
'title' => __('Chat'),
'url' => '/chat',
'route' => null,
]);
if (!$user->exists) {
$user->fill([
'target' => '_self',
'icon_class' => null,
'color' => '#000000',
'parent_id' => null,
'order' => 1,
])->save();
}
}
}
But an error occured when seeding saying this:
I've tried to run this but it didn't help.
apt install php7.2-cli
How to correct the error?
P.S. I've tried to google this error but I didn't find anything.
The problem solved. I misspelled the first "p" letter in the command.
I am using laravel back and and I have two tables called bundles and study. I added a drop down fields in the form from bundleCrudController. But I just want to add only those values in the drop down list which studies are created by the logged in user not all the data from studies table.
Here is my code to add data in drop down list -
$this->crud->addField([
'name' => 'studies',
'label' => 'Studies',
'type' => 'select2_from_array',
'options' => $this->Study->getUnallocatedStudies($entryId),
'allows_null' => false,
'hint' => 'Search for the studies you would like to add to this bundle',
'tab' => 'Info',
'allows_multiple' => true
]);
$this->crud->addColumn([
'label' => 'Studies',
'type' => "select_multiple",
'name' => 'bundle_id',
'entity' => 'studies',
'attribute' => 'name',
'model' => "App\Models\Study",
]);
So pls help me to resolve the problem to add only those records in the dropdownlist created by the logged in user not all records.. Thanx
I think the best way would be to create an additional model, UserStudy, that:
extends Study;
has a global scope for filtering for what the current user can see;
It should look something like this:
<?php
namespace App\Models;
use App\Models\Study;
use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class UserStudy extends Study
{
/**
* The "booting" method of the model.
*
* #return void
*/
protected static function boot()
{
parent::boot();
// filter out the studies that don't belong to this user
if (Auth::check()) {
$user = Auth::user();
static::addGlobalScope('user_id', function (Builder $builder) use ($user) {
$builder->where('user_id', $user->id);
});
}
}
}
You'll then be able to use this UserStudy model in your field definition, instead of Study. Just replace App\Models\Study with App\Models\UserStudy.
Hope it helps. Cheers!
I haven't been able to find a solution that solves this. I am trying to query my database for a list of groups to which a user belongs. Users can be in multiple groups, and groups can have multiple users.
I have "users", "groups", and "groups_users" tables. Each has an "id" field, and the "groups_users" table has two other fields, "group_id" and "user_id".
I think all the tables are properly formed.
My User.php, and Group.php model files look like this
//app/Model/User.php
class User extends AppModel {
public $recursive = 1;
public #hasAndBelongsToMany = array(
'Group' => array(
'className' => 'Group',
'joinTable' => 'groups_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'group_id'
)
);
}
//app/Model/Group.php
class Group extends AppModel {
public $recursive = 1;
public #hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'groups_users',
'foreignKey' => 'group_id',
'associationForeignKey' => 'user_id'
)
);
}
Then, in my Controller file I have this
//app/Controller/ProjectController.php
class ProjectController extends AppController {
public $uses = array('Groups', 'Users');
...
$this->set('groupsForUser', $this->Groups->find('all', array(
'conditions' => array('Users.UserName' => 'testuser1')
));
}
Every time I try to display the data, I get the error message
Error: ..... Unknown column 'Users.UserName' in 'where clause'
And it shows me the SQL it's trying to run:
SELECT Groups.id, ... FROM accounts.groups AS Groups WHERE Users.UserName = 'testuser1'
Obviously the association between the tables isn't happening properly and the SQL query it is sending in isn't joined properly, but I can't figure out what's going wrong here. I've tried varieties like
.....$this->Groups->Users->find(....
And stuff like that, but nothing seems to work.
Help!
I think You should use "User.UserName" instead of "Users.UserName" in your ProjectController.php because you have "User" in your associations So model name should be same.
//app/Controller/ProjectController.php
class ProjectController extends AppController {
public $uses = array('Groups', 'User');
...
$this->set('groupsForUser', $this->Groups->find('all', array(
'conditions' => array('User.UserName' => 'testuser1')
));
}
I had to take a completely different approach to the problem. It's mostly "Cake-y".
I simplified the models a bit by taking out the $recursive bit and trimmed down the HABTM part, removing the joinTable, foreignKey, and associationForeignKey bits)
The ProjectController got the code:
public $uses = array('Group', 'User');
$arrayGroupsForUser = array();
....
$results = $this->User->Find('first', array(
'conditions' => array('User.UserName' => 'testuser1')
));
foreach($results['Group'] as $result) {
array_push($arrayGroupsForUser, $result['name']);
}
$this->set('groupsForUser', $arrayGroupsForUser);
(Thank you ned stark for noting the need for a singular "User". I can't upvote your answer with my limited reputation yet.)
The "$this->set(.....);" line is to pass just the array of group names to the View to use.
This link http://rottmann.net/2012/07/cakephp-hasandbelongstomany-relationship-queries-demystified/ was a big help in helping me solve this.
When designing a relationship in Datamapper one is bound to call the relationship the same name as the related object, which is not too handy when you have something like Application_Model_User as a class name. For those of you who will rush to say that there is a configuration option with "class" key, I know. Been there tried that. It only works for getting a related object, not for updating them.
Here is a code snippet to reproduce the problem:
// User Model
class UserModel extends Datamapper
{
public $table = 'users';
public $has_many = array(
'roles' => array(
'class' => 'RoleModel',
'other_field' => 'usermodel',
'join_other_as' => 'role',
'join_self_as' => 'user',
'join_table' => 'users_roles'
),
);
}
class RoleModel extends DataMapper
{
public $table = 'roles';
public $has_many = array(
'usermodel' => array('class' => 'UserModel',
'other_field' => 'roles',
'join_other_as'=> 'user',
'join_self_as' => 'role',
'join_table' => 'users_roles' )
);
}
// controller code. Make sure you have a role with INT id = 2, and a user with INT id = 5 in your db
$user = new UserModel(2);
$role = new RoleModel(5);
$user->save($role);
This code gives an "Unable to relate usermodel with rolemodel." error, however it does work properly (meaning a new record is inserted in the join table user_roles) if the relation is renamed from "roles" to "rolemodel".
So, if there are any avid users of CI's Datamapper that could help, please let me know how to properly define relationships.
UPDATE
You can save an object as a relation using the relationship key:
$object->save( $related, $relationship_key ).
So you would need to use
$user->save($role, "roles");
See the bottom of this web page:
http://datamapper.wanwizard.eu/pages/save.html
Leaving this bit in case it helps someone else out.
It looks like you want to have a custom name on a relationship. (That's what I get after wading through all of the cynicism) -
You get to name the relationship anything that you want with the key in the relationship array. So, in the following snippet, you use book <-- this does or does not have to be the same name as the class - that's what the class key is for.
class Author extends DataMapper {
$has_many = array(
'book' => array( // YOU USE THIS KEY TO NAME THE RELATIONSHIP
'class' => 'book',
'other_field' => 'author',
'join_self_as' => 'author',
'join_other_as' => 'book',
'join_table' => 'authors_books'
)
);
}
If this is not working for you, my guess is you have something else wrong in the set up of your relationships.
http://datamapper.wanwizard.eu/pages/advancedrelations.html
Is possible to remove a column in a migration postUp() method or is only intended to be used for data manipulation?
I don't know what version of Doctrine Migrations you are using. However, I just ran across this same question when working with Doctrine Migrations 2.0 and started digging into the code. When looking at how a Version is constructed, it appears that using the Schema object to make changes in the postUp() method does not take effect.
However, upon further consideration, this really makes sense. Each migration version is intended to modify the database structure. This takes place in the up() and down() methods of each migration. postUp() seems to be intended mostly for post structural changes cleanup (i.e. manipulating data). Any further structural modifications that you had intended on making in the postUp() method are should be made in a subsequent migration file.
For example, I was attempting to create a new table that was going to hold two columns from a previous table. I intended to drop those columns from the previous table after I had migrated data over to the new table. The code follows:
class Version20110512223208 extends AbstractMigration
{
protected $customerRepository;
protected $evernoteRepository;
public function up(Schema $schema)
{
$table = $schema->createTable('customer_evernote');
$table->addOption('type', 'INNODB');
$table->addOption('charset', 'utf8');
$table->addOption('collate', 'utf8_unicode_ci');
// Columns.
$table->addColumn('customer_id', 'bigint', array(
'length' => 20,
'notnull' => true,
'autoincrement' => false));
$table->addColumn('integration_date', 'datetime', array('notnull' => true));
$table->addColumn('oauth_token', 'string', array(
'length' => 255,
'notnull' => true));
$table->addColumn('oauth_shard_id', 'string', array(
'length' => 4,
'notnull' => true,
'fixed' => true));
$table->setPrimaryKey(array('customer_id'), 'pk_customer_id');
$table->addForeignKeyConstraint($schema->getTable('customer'), array('customer_id'), array('id'));
}
public function down(Schema $schema)
{
$schema->dropTable('customer_evernote');
}
public function preUp(Schema $schema)
{
$this->addSql("ALTER TABLE `customer` ENGINE = INNODB");
}
public function postUp(Schema $schema)
{
$this->skipIf($this->version->isMigrated() !== true, 'postUp can only apply if migration completes.');
// Copy the data from the customer table into the newly created customer_evernote table.
$this->doctrine = \Zend_Registry::get('doctrine');
$this->entityManager = $this->doctrine->getEntityManager();
$this->customerRepository = $this->entityManager->getRepository('My\Entity\Customer');
$this->evernoteRepository = $this->entityManager->getRepository('My\Entity\CustomerEvernote');
$customers = $this->customerRepository->findAll();
foreach ($customers as $customer)
{
$evernoteRecord = new \My\Entity\CustomerEvernote();
$evernoteRecord->setCustomerId($customer->getId());
$evernoteRecord->setCustomer($customer);
$evernoteRecord->setOauthToken($customer->getEvernoteOauthToken());
$evernoteRecord->setOauthShardId($customer->getEvernoteOauthShardId());
$evernoteRecord->setIntegrationDate(new \DateTime("now"));
$this->evernoteRepository->saveEvernote($evernoteRecord);
}
// Drop the columns from the existing customer table.
$table = $schema->getTable('customer');
$table->dropColumn('evernote_oauth_token');
$table->dropColumn('evernote_oauth_shard_id');
}
public function preDown(Schema $schema)
{
// Create the existing columns in the customer table.
$table = $schema->getTable('customer');
$table->addColumn('evernote_oauth_token', 'string', array(
'length' => 255,
'notnull' => false));
$table->addColumn('evernote_oauth_shard_id', 'string', array(
'length' => 4,
'notnull' => false,
'fixed' => true));
// Copy the data to the customer table.
$this->doctrine = \Zend_Registry::get('doctrine');
$this->entityManager = $this->doctrine->getEntityManager();
$this->customerRepository = $this->entityManager->getRepository('My\Entity\Customer');
$this->evernoteRepository = $this->entityManager->getRepository('My\Entity\CustomerEvernote');
$integrations = $this->evernoteRepository->findAll();
foreach ($integrations as $integration)
{
$integration->getCustomer()->setEvernoteOauthToken($integration->getOauthToken());
$integration->getCustomer()->setEvernoteOauthShardId($integration->getOauthShardId());
$this->customerRepository->saveCustomer($integration->getCustomer());
}
}
}
In reality, if I were to move the code at the end of postUp() to a new version's up() and the code at the beginning of the preDown() to a new version's down() method, I get the same results as in the class above, just performed in two separate steps. With this approach, I guarantee that I have structural modifications strictly taking place in my up and down methods.