In my laravel 5.7 app in console I created new table migration script and seeder :
php artisan make:migration create_page_content_images_table --create="page_content_images"
php artisan make:seeder PageContentImagesWithInitData
Both files were created ok and I filled them database/migrations/2018_12_04_120422_create_page_content_images_table.php:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePageContentImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('page_content_images', function (Blueprint $table) {
$table->increments('id');
$table->integer('page_content_id')->unsigned();
$table->foreign('page_content_id')->references('id')->on('page_contents')->onDelete('RESTRICT');
$table->string('filename', 255);
$table->boolean('is_main')->default(false);
$table->boolean('is_video')->default(false);
$table->string('video_type', 10)->nullable();
$table->string('video_ext', 5)->nullable();
$table->smallInteger('video_width')->nullable();
$table->smallInteger('video_height')->nullable();
$table->string('info', 255)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->unique(['page_content_id', 'filename'], 'page_contents_page_content_id_filename_unique');
$table->index(['page_content_id', 'is_main'], 'page_contents_page_content_id_is_main');
$table->index(['page_content_id', 'is_video', 'filename'], 'page_contents_page_content_id_is_video_filename');
$table->index(['created_at'], 'page_content_message_documents_created_at_index');
});
Artisan::call('db:seed', array('--class' => 'PageContentImagesWithInitData')); //database/seeds/PageContentImagesWithInitData.php
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('page_content_images');
}
}
and database/seeds/PageContentImagesWithInitData.php :
<?php
use Illuminate\Database\Seeder;
class PageContentImagesWithInitData extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('page_content_images')->insert([
'id' => 1,
'page_content_id' => 1, // About
'filename' => 'your_vote.jpg',
'is_main' => false,
'is_video' => false,
'video_type' => null,
'video_ext' => null,
'video_width' => null,
'video_height' => null,
'info' => 'Site slogan image',
]);
DB::table('page_content_images')->insert([
'id' => 2,
'page_content_id' => 1, // About
'filename' => 'our_boss.jpg',
'is_main' => false,
'is_video' => false,
'video_type' => null,
'video_ext' => null,
'video_width' => null,
'video_height' => null,
'info' => 'Our boss photo',
]);
DB::table('page_content_images')->insert([
'id' => 3,
'page_content_id' => 1, // About
'filename' => 'our_main_manager.jpg',
'is_main' => false,
'is_video' => false,
'video_type' => null,
'video_ext' => null,
'video_width' => null,
'video_height' => null,
'info' => 'Our main manager',
]);
DB::table('page_content_images')->insert([
'id' => 4,
'page_content_id' => 2, // Contact Us
'filename' => 'office_building.jpeg',
'is_main' => true,
'is_video' => false,
'video_type' => null,
'video_ext' => null,
'video_width' => null,
'video_height' => null,
'info' => 'Office building',
]);
DB::table('page_content_images')->insert([
'id' => 5,
'page_content_id' => 2, // Contact Us
'filename' => 'office.jpeg',
'is_main' => true,
'is_video' => false,
'video_type' => null,
'video_ext' => null,
'video_width' => null,
'video_height' => null,
'info' => 'Our Office',
]);
}
}
The problem is that running migration command I got error:
ReflectionException : Class PageContentImagesWithInitData does not exist
at /mnt/_work_sdb8/wwwroot/lar/Votes/vendor/laravel/framework/src/Illuminate/Container/Container.php:779
I checked and do not see any misspelling or case issue...
I run in console next commands :
php artisan config:cache
composer dump-autoload
But I got error anyway...
Why error and how to fix it?
Thanks!
I had similar issue and I failed to find valid decision, after some search I found
these 2 files
/vendor/composer/autoload_classmap.php
/vendor/composer/autoload_static.php
which included my prior seeder classes, but not current I failed to run
I manually removed vendor directory and run
composer install
and cleared cache
That helped!
You can try this way!
I think the error is with your seeder namespaces,
you can use --path instead of --class, Try this kind of thing,
Artisan::call('db:seed', array('--path' => 'path/to/my/seed'));
Related
when I first made a migration file for table users, the public function down() in the migration file was empty. when I run php spark migrate the table users was created.
then I generated another migration file with php spark make:migration users, made a few adjustments according to the new table structure and put $this->forge->dropTable('users'); in the public function down(). but when I run php spark migrate again, the users table doesn't have the new field..
I'm using codeigniter 4 and mysql. here's my code
UserModelphp
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
// added created_at and updated_at
protected $allowedFields = ['username', 'password', 'foto', 'nama', 'email', 'telepon', 'created_at', 'updated_at'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
}
first migration file
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Users extends Migration
{
public function up()
{
// tabel users
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 7,
'auto_increment' => true,
],
'username' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => false,
],
'password' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'profile_pic' => [
'type' => 'VARCHAR',
'constraint' => 50,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => 50,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'telepon' => [
'type' => 'VARCHAR',
'constraint' => 10,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
// hapus tabel users
}
}
new migration file
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Users extends Migration
{
public function up()
{
// tabel users
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 7,
'auto_increment' => true,
],
'username' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => false,
],
'password' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => false,
],
'foto' => [
'type' => 'VARCHAR',
'constraint' => 50,
],
'nama' => [
'type' => 'VARCHAR',
'constraint' => 50,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'telepon' => [
'type' => 'VARCHAR',
'constraint' => 10,
],
'created_at DATETIME DEFAULT CURRENT_TIMESTAMP',
'updated_at DATETIME DEFAULT CURRENT_TIMESTAMP',
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
// hapus tabel users
$this->forge->dropTable('users');
}
}
can someone tell me what I'm doing wrong? any help is appreciated
Explanation:
The down() method isn't called when you execute php spark migrate.
The down() method is run when you perform a migration rollback process using php spark migrate:rollback.
Solution:
Add the $this->forge->dropTable('users'); line of code at the beginning of the up() method of the "new migration file".
new migration file
// ...
class Users extends Migration
{
public function up()
{
$this->forge->dropTable('users');
// ...
}
// ....
}
The purpose of the down() method is to "reverse" everything performed in the up() method.
Extra Notes:
Considering that in your new migration, you're only renaming an existing table column (profile_pic -> foto) and adding timestamp columns, it would make more sense if you specified a more meaningful "migration name".
In addition, instead of dropping & recreating the existing table, modify the table instead.
I.e:
new migration file
A. Command (Create the new migration):
php spark make:migration alter_users_rename_profile_pic_add_timestamps
B. Generated migration.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AlterUsersRenameProfilePicAddTimestamps extends Migration
{
private $tableName = "users";
public function up()
{
$this->forge->modifyColumn($this->tableName, [
"profile_pic" => [
'name' => 'foto',
'type' => 'VARCHAR',
'constraint' => 50,
]
]);
$this->forge->addColumn($this->tableName, [
'created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
'updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
]);
}
public function down()
{
$this->forge->modifyColumn($this->tableName, [
"foto" => [
'name' => 'profile_pic',
'type' => 'VARCHAR',
'constraint' => 50,
]
]);
$this->forge->dropColumn($this->tableName, ["created_at", "updated_at"]);
}
}
can someone help me to understand how can I use attribute casting if I am inserting data with DB seeder (and retrieve it)
this is part of the seeder
DB::table('events')->insert([
[
'title' => 'prizes',
'description' => serialize([
"text" => "General description..."
]),
'language' => 'en',
'time_start' => null,
'time_end' => null,
'lat' => null,
'lng' => null,
]
]);
this way I do have serialized data in my database, but when I do
$events = Event::with('user')->where('child','=',null)->get();
I get description is null
(don't worry about user its null by default)
this is my Event model
class Event extends Model
{
protected $table = 'events';
//
public function user()
{
return $this->hasOne('App\User','id');
}
protected $casts = [
'description' => 'array',
];
}
what am I missing here?
According to the doc, Eloquent array casting serializes array into JSON:
The array cast type is particularly useful when working with columns that are stored as serialized JSON
So you should insert it like this:
DB::table('events')->insert([[
'title' => 'prizes',
'description' => json_encode(["text" => "General description..."]),
'language' => 'en',
'time_start' => null,
'time_end' => null,
'lat' => null,
'lng' => null,
]]);
As a side note, serialize belongs to PHP core and it does not produce JSON.
I'm using my own User model class that is not derived from Eloquent. I use a database driver for authentification, which works fine.
However, Auth::user() returns a class of type GenericUser. Is there a way to assign a custom user model to the Auth class?
I tried auth config...
'users' => [
'driver' => 'database',
'table' => 'users',
'model' => App\Models\User::class
],
But it doesn't work. Perhaps this functionality doesn't exist.
Edit:
I don't want to use Active record, I have a Data Mapper package for that. My user model looks like this...
<?php
class User extends Model
{
use Notifiable, HasApiTokens, CanResetPassword;
use Authenticatable, Authorizable;
protected $attributes = [
'id' => null, 'roleId' => null,
'email' => null, 'phone' => null,
'firstName' => null, 'lastName' => null,
'password' => null, 'rememberToken' => null,
'registrationLocation' => null,
'data' => null,
'verified' => 0,
'createdAt' => null, 'updatedAt' => null,
];
public function __construct(array $attributes = [])
{
$this->fill($attributes);
}
}
Model is extended from the data mapper package's class Entity.
I was wondering if someone can help me.
I am having trouble seeding a database in laravel using seeder, it keeps throughing this error:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
When running php artisan db:seed
the seeder in question is: GroupTableSeeder.php and the code in the file is:
<?php
class GroupTableSeeder extends Seeder {
public function run()
{
DB::table('groups')->truncate();
$permissions = array( 'system' => 1, );
$group = array(
array(
'name' => 'agency',
'permissions' => $permissions,
'created_at' => new DateTime,
'updated_at' => new DateTime
),
);
DB::table('groups')->insert($group);
}
}
In the DatabaseSeeder.php I have:
public function run()
{
Eloquent::unguard();
$this->call('GroupTableSeeder');
$this->command->info('Group table seeded!');
}
I am trying to populate the Groups table with a user role I am currently using https://cartalyst.com/manual/sentry#groups
Any help would be much appreciated.
Cheers,
Chris
Found the answer, I needed to do:
Sentry::getGroupProvider()->create(array(
'name' => 'Agency',
'permissions' => array('admin' => 1),
));
Instead of:
$permissions = array( 'system' => 1, );
$group = array(
array(
'name' => 'agency',
'permissions' => $permissions,
'created_at' => new DateTime,
'updated_at' => new DateTime
),
);
I've created custom doctrine(1.2) behavior which should create tables for models (very simmilar to i18n behavior). I see this tables in schema.sql, and if i execute it everything is fine, but this is no such tables if my migrations diff (doctrine:generate-migrations-diff).
What i'm doing wrong?
class DescriptionableGenerator extends Doctrine_Record_Generator
{
protected $_options = array(
'className' => '%CLASS%Description',
'tableName' => '%TABLE%_description',
'fields' => array(),
'generateFiles' => false,
'table' => false,
'pluginTable' => false,
'children' => array(),
'options' => array(),
'cascadeDelete' => true,
'appLevelDelete' => false
);
public function __construct(array $options = array())
{
$this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options);
}
public function buildRelation()
{
$this->buildForeignRelation('Descriptions');
$this->buildLocalRelation();
}
public function setTableDefinition()
{
$this->hasColumn('lang', 'char', '2', array('notnull' => true));
$this->hasColumn('field', 'string', '255', array('notnull' => true));
$this->hasColumn('title', 'string', '255', array('notnull' => true));
$this->hasColumn('description', 'clob');
$this->hasColumn('compulsory', 'boolean', 1, array('notnull' => true, 'default' => 0));
$this->addListener(new DescriptionableListener());
}
}
Solved!
Problem appears due to command "php symfony doctrine:build-model".
So, if you have the same problem you should:
Remove your behavior from schema.
Execute "php symfony doctrine:build-model".
Add your behavior to schema.
Run "php symfony doctrine:generate-migrations-diff".
Chears! %)