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
),
);
Related
I try to add data with seed in laravel 5.4, let's say I have 10 category and I added them by seed to my database now I also have another seed for subcategories but before I add my subcategories I want to tell which one is belongs to what category that I imported before. how would I do that?
Update:
I found my question might be confusing for some people so i try to explain a bit more,
this is my category seed.
<?php
use Illuminate\Database\Seeder;
class CategoriessTableSeeder extends Seeder {
public function run()
{
DB::table('categories')->delete();
$categories = array(
array('name' => 'Accounting/Finance', 'slug' => 'hccounting_finance'),
array('name' => 'Admin/Human Resources', 'slug' => 'admin_human_resources'),
array('name' => 'Arts/Media/Communications', 'slug' => 'arts_media_communications'),
array('name' => 'Building/Construction', 'slug' => 'building_construction'),
array('name' => 'Computer/Information Technology', 'slug' => 'computer_information_technology'),
array('name' => 'Education/Training', 'slug' => 'education_training'),
array('name' => 'Engineering', 'slug' => 'engineering'),
array('name' => 'Healthcare', 'slug' => 'healthcare'),
array('name' => 'Hotel/Restaurant', 'slug' => 'hotel_restaurant'),
array('name' => 'Manufacturing', 'slug' => 'manufacturing'),
array('name' => 'Sales/Marketing', 'slug' => 'sales_marketing'),
array('name' => 'Sciences', 'slug' => 'sciences'),
array('name' => 'Services', 'slug' => 'services'),
array('name' => 'Others', 'slug' => 'others'),
);
DB::table('categories')->insert($categories);
}
}
I have another similar with this for subcategories here it is:
<?php
use Illuminate\Database\Seeder;
class SubategoriessTableSeeder extends Seeder {
public function run()
{
DB::table('subcategories')->delete();
$subcategories = array(
array('name' => 'Audit & Taxation Jobs', 'slug' => 'audit_taxation_jobs', 'category_id' => ''),
);
DB::table('subcategories')->insert($subcategories);
}
}
in this sample 'category_id' => '' has to get the id/name of 'Accounting/Finance category in category seed .
now my question is how?
UPDATE 2:
Error's
[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity
constraint violation: 1451 Cannot delete or update a parent row: a
foreign key constraint fails (jobid.ads, CONSTRAINT ads_subcateg
ory_id_foreign FOREIGN KEY (subcategory_id) REFERENCES
subcategories (id)) (SQL: delete from subcategories)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
(jobid.ads, CONSTRAINT ads_subcateg
ory_id_foreign FOREIGN KEY (subcategory_id) REFERENCES subcategories (id))
Code used:
<?php
use Illuminate\Database\Seeder;
use Carbon\Carbon;
class SubcategoriesTableSeeder extends Seeder {
public function run()
{
DB::table('subcategories')->delete();
$categoryFinance = Category::select("id")->whereSlug("hccounting_finance")->firstOrFail();
$subcategories = array(
array('name' => 'Audit & Taxation Jobs', 'category_id' => $categoryFinance, 'slug' => 'audit_taxation_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
array('name' => 'Banking/Financial Jobs', 'category_id' => $categoryFinance, 'slug' => 'banking-financial_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
array('name' => 'Corporate Finance/Investment Jobs', 'category_id' => $categoryFinance, 'slug' => 'corporate_finance_investment_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
array('name' => 'General/Cost Accounting Jobs', 'category_id' => $categoryFinance, 'slug' => 'general_cost_accounting_jobs', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
);
$categoryAdmin = Category::select("id")->whereSlug("admin_human_resources")->firstOrFail();
$subcategories = array(
array('name' => 'testing', 'slug' => 'tesingsubs', 'category_id' => $categoryAdmin, 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s')),
);
DB::table('subcategories')->insert($subcategories);
}
}
In order to relate your categories to subcategories, you should follow the logic (depending on your relationship - N-1 N-N) in the docs (https://laravel.com/docs/5.4/eloquent-relationships). It seems that you need the attach() method.
So after creating the category entry, if you have followed the schema convention you can apply logic for all kind or relationships, even for polymorphic ones.
Edit:
After your edit it seems that you need a way to access the entries of your table again in order to relate them.
So, you can :
$categoryFinance = Category::select("id")->whereSlug("hccounting_finance")->firstOrFail();
in your SubategoriessTableSeeder run() function before creating your array.
And then give that id in your subcategory_id. The same will be for all categories you need to relate.
Edit 2
Please check again that your foreign keys are correct. In that case you cannot delete the subcategories table because Categories "need" subid. And that's where constraint violation comes from. You don't need to delete these tables.. You just need to "feed-seed" them.
So try to remove the "delete" statements.
Edit 3
I think the error is obvious now.. There is no Category with id of 2 in your database. But again, check if the keys are associated correctly (this is an SQL and not a Laravel issue).
Run migrations if any, and seeders again, with the correct order (first categories and then subcategories - first the dependency and then the dependent one in general)
I had user migration:
$table->enum('type',['seller','buyer'])->default('seller');
I want when using ModelFactory how to get random value seller or buyer?
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'firstName' => $faker->name,
'lastName' => $faker->name,
'username' => $faker->unique()->username,
'email' => $faker->unique()->safeEmail,
'password' => md5('user123'),
'bio' => $faker->sentence(3, true),
'type' => ???,
];
});
Make use of randomElement method
'type' => $faker->randomElement(['seller', 'buyer']),
Laravel version >= 5.6
use Illuminate\Support\Arr;
$array = [1, 2, 3, 4, 5];
$random = Arr::random($array);
// 4 - (retrieved randomly)
"type" => Arr::random($array);
Just in case that anyone is looking for the answer of this question with newer version of Laravel and PHP, you can utilize the enum in PHP like so:
<?php
namespace App\Enums;
enum UserTypeEnum: string
{
case SELLER = 'seller';
case BUYER = 'buyer';
}
and then your factory will look like this:
<?php
namespace Database\Factories;
use App\Enums\UserTypeEnum;
use Illuminate\Database\Eloquent\Factories\Factory;
class TaskFactory extends Factory
{
public function definition()
{
return [
'firstName' => fake()->firstName,
'lastName' => fake()->lastName,
'username' => fake()->unique()->username,
'email' => fake()->unique()->safeEmail,
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password,
'bio' => fake()->sentence(3, true),
'type' => fake()->randomElement(UserTypeEnum::cases()),
];
}
}
And also if your type column is nullable you can have your seeder type like fake()->randomElement([...UserTypeEnum::cases(), null]) as well.
Below is my model factory.
$factory->define(App\Business::class, function (Faker\Generator $faker){
return [
'name' => $faker->bs,
'slug' => $faker->slug,
'address' => $faker->streetAddress,
'phone_no' => $faker->phoneNumber,
'mobile_no' => $faker->phoneNumber,
'email' => $faker->companyEmail,
'website' => $faker->domainName,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'location' => $faker->city,
'business_days_from' => $faker->dayOfWeek,
'business_days_to' => $faker->dayOfWeek,
'description' => $faker->text,
'user_id' => $faker->factory(App\User::class),
];
});
and This my database seeder class
class DatabaseSeeder extends Seeder
{
public function run()
{
factory(App\Business::class, 300)->create();
}
}
But when I execute php artisan db:seed ...it does not work..
What should be the workaround here..any help would be appreciated..
you can get all ids using pluck (lists is depricated for laravel >= 5.2)
$userIds = User::all()->pluck('id')->toArray();
and get a random id for FK column:
'user_id' => $faker->randomElement($userIds)
You may also attach relationships to models using Closure attributes in your factory definitions.
'title' => $faker->title,
'content' => $faker->paragraph,
'user_id' => function () {
return factory(App\User::class)->create()->id;
}
I just found the workaround .. I replaced
'user_id' => $faker->factory(App\User::class),
with
'user_id' => $faker->randomElement(User::lists('id')->toArray()),
and that solves the problem for now..
i have to update a table and change the value inside it and the table have many column inside it. i tried to use query builder and here is my current code
the query is inside the public function ugetstd($id)
public function ugetstd($id) //update
{
$rules = array(
'firstname' => 'required|max:80|regex:/^[\p{L}\p{N} - ]+$/u',
'middlename' => 'required|max:50|regex:/^[\p{L}\p{N} -]+$/u', //more here
);
$messages = array(
'firstname.required' => 'First name is required',
'firstname.max' => 'First name can only contain 80 characters' //more here
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails())
{
return Redirect::to('view_students/' . $id)
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
DB::table('dbo_students')->where('StudentID', $id )
->update
(
array
(
'FirstName' => Input::get('firstname'),
'MiddleName' => Input::get('middlename'),
'LastName' => Input::get('lastname'),
'CurrentStatusID' => Input::get('scs'),
'Sex' => Input::get('sex'),
'ReligionID' => Input::get('rel'),
'EthnicityID' => Input::get('eth'),
'StreetAddress' => $enAdd,
'CityID' => Input::get('city'),
'YearLevelID' => Input::get('yearlevel'),
'Telephone' => Input::get('telephone'),
'Birthdate' => Input::get('date'),
'Birthplace' => Input::get('birthplace'),
'SchoolLastAttended' => Input::get('schoollastattended'),
'LastGradeCompleted' => Input::get('lastgradecompleted'),
'CurrentModuleLeft' => Input::get('currentmoduleleft'),
'CurrentModuleCriticalLevel' => Input::get('modulecriticallevel'),
'StudentDescription' => Input::get('description')
)
);
return Redirect::to('view_students/' . $id);
}
}
the thing is it does not execute the code. it does not update anything and it does not throw any error. any ideas what i am doing wrong? thanks
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! %)