Problem with seeding users to database in Laravel - php

I am trying to seed users in database but I get error saying
Symfony\Component\Debug\Exception\FatalThrowableError : Call to a member function random() on bool
I have users table and genders table with gender_id in users table that points to Man or Woman column in genders table with hasMany relationship. I want to be able to write gender_id automatically in users table when I seed the database and create a new user. Currently with this code I get that error from above and NULL in gender_id column, but rest it inserts correctly in both users and genders table. When I remove random() function then it inserts always 1 in gender_id, but I want to be able to write 1 or 2 randomly. Also when I dump $genders it returns TRUE. Is there some way around this, any help is appreciated. Here is my code.
UserSeeder.php
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$genders = DB::table('genders')->insert([
[
'genders' => 'Woman',
],
[
'genders' => 'Woman Looking For Woman',
],
[
'genders' => 'Man',
]
]);
//dd($genders);
DB::table('users')->insert([
'gender_id' => $genders->random(),
'name' => 'authuser',
'email' => 'authuser#auth.com',
'email_verified_at' => now(),
'password' => Hash::make('auth123456'),
'age' => 18,
'remember_token' => Str::random(10),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
}
users table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('gender_id')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->default();
$table->integer('age')->default()->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
genders table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGendersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('genders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('genders');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('genders');
}
}
User.php
public function gender()
{
return $this->belongsTo(Gender::class, 'gender_id', 'id');
}
Gender.php
public function users()
{
return $this->hasMany(User::class, 'gender_id', 'id');
}

You can pluck your id values from Gendre and do randomly on that like this:
$genders = DB::table('genders')->insert([
['genders' => 'Woman'],
['genders' => 'Woman Looking For Woman'],
['genders' => 'Man']
]);
$gendreIds = Genders::pluck('id');
DB::table('users')->insert([
'gender_id' => $gendreIds->random(),
...
]);
This will give you gender which exists in database.
Sometimes seed wouldn't give you id's from 1 to 3.
So I think it's not best solution to use rand(1,3).
Good luck!

In your user creation method
Instead of
'gender_id' => $genders->random(),
you can use this
'gender_id' => rand(1,3),

No need to add genders here.You can do that in other seeder or manually do that.Here in your genders id should be in 1,2 & 3 .fixed.THen you can use rand() function here.rand() is a php function .rand() define a random number & you can fixed it value like rand(min,max) so just here use this rand(1,3)
public function run()
{
$genders = DB::table('genders')->insert([
[
'genders' => 'Woman',
],
[
'genders' => 'Woman Looking For Woman',
],
[
'genders' => 'Man',
]
]);//your wish to seed this gender in here
DB::table('users')->insert([
'gender_id' => rand(1,3),
'name' => 'authuser',
'email' => 'authuser#auth.com',
'email_verified_at' => now(),
'password' => Hash::make('auth123456'),
'age' => 18,
'remember_token' => Str::random(10),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}

Related

Idgenerator laravel 8, how to fix Exception "table field type is bigint but prefix is string"

why does this message always appear?
even though I want to make an id with 2 dots like = 190772.2021.00000001
can't add '.' (dots) like that can only add 1 dots only 1907722021.00000001
factory.php
namespace Database\Factories;
use App\Models\Anggota;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\User;
use Haruncpi\LaravelIdGenerator\IdGenerator;
class AnggotaFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Anggota::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
$tgl = $this->faker->date;
return [
'id_user' => User::factory(),
'no_anggota' => IdGenerator::generate([
'table' => 'anggotas',
'length' => 19,
'prefix' => date('dmy', strtotime($tgl)).date('.Y.')
]),
'nama_lengkap' => $this->faker->name,
'tempat_lahir' => $this->faker->cityPrefix,
'tanggal_lahir' => $tgl,
'nama_instansi' => $this->faker->word,
];
}
}
file migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAnggotasTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('anggotas', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('id_user')->unique();
$table->string('no_anggota');
$table->string('nama_lengkap');
$table->string('tempat_lahir');
$table->date('tanggal_lahir');
$table->string('nama_instansi');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('anggotas');
}
}
whereas column "no_anggota" in the schema database is of type "string" but appears "table field type is bigint but prefix is string"
how to solve it so that the result = 190772.2021.00000001
help me, thanks
The laravel ID generator package by default use table's id column. According to your need, the documentation says (example 4), you have to pass field also.
Your required output: 190772.2021.00000001 ( length 20 with two dots)
Solution: Just pass 'field' => 'no_anggota' and 'length' => 20
$tgl = $this->faker->date;
$idConfig = [
'table' => 'anggotas',
'field' => 'no_anggota',
'length' => 20,
'prefix' => date('dmy', strtotime($tgl)).date('.Y.')
];
return [
'id_user' => User::factory(),
'no_anggota' => IdGenerator::generate($idConfig),
'nama_lengkap' => $this->faker->name,
'tempat_lahir' => $this->faker->cityPrefix,
'tanggal_lahir' => $tgl,
'nama_instansi' => $this->faker->word,
];

Getting ErrorException Trying to get property of non-object in laravel

I'm trying to store my form data in my laravel application on the store method.
public function store(Request $request)
{
$this->validate($request, [
'subDomainName' => 'required',
'subDomainSuffix' => 'required',
'lang' => 'required',
'themeid' => 'required',
'paymentoption' => 'required',
'packageType' =>'required',
'domain' => 'unique:apps',
]);
$user = Auth::user();
$fullDomain = $request->domain;
$dbName = $this->dumpNewDB($fullDomain);
$appId = $this->getNextId();
// create record in app table
Website::create([
'domain' => $fullDomain,
'masterUserId' => $request->user,
'dbName' => $dbName,
'host' => env('DB_HOST', '127.0.0.1'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'root'),
'theme' => $request->themeid,
'lang' => $request->lang,
'status' => 1,
'package_type' => $request->packageType,
'payment_option' => $request->paymentoption,
'isAppCreated' => 1,
'isDefault' => 0,
]);
}
and also i have a function to dump a db as well
public function dumpNewDB($domain)
{
Tenant::new()->withDomains($domain)->save();
$tenant = DB::table('domains')->where('domain', $domain)->first();
\Artisan::call('tenants:migrate', [
'--tenants' => [$tenant->tenant_id]
]);
\Artisan::call('tenants:seed', [
'--tenants' => [$tenant->tenant_id]
]);
return $tenant->tenant_id;
}
When ever I run the following functions I'm getting following error,
ErrorException
Trying to get property 'tenant_id' of non-object
Database migration for my apps table as follows,
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAppsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('apps', function (Blueprint $table) {
$table->bigIncrements('appId');
$table->string('domain')->unique();
$table->bigInteger('masterUserId')->unsigned();
$table->string('dbName');
$table->string('host');
$table->string('username');
$table->string('password');
$table->string('theme');
$table->string('lang');
$table->date('renewDate')->nullable();
$table->date('renewedDate')->nullable();
$table->tinyInteger('status');
$table->bigInteger('package_type')->unsigned();
$table->string('payment_option');
$table->tinyInteger('isAppCreated');
$table->string('stripeCustomerId')->nullable();
$table->tinyInteger('subscrStatus')->nullable();
$table->dateTime('reSubTime')->nullable();
$table->dateTime('upgradeTime')->nullable();
$table->tinyInteger('isDefault')->nullable();
$table->foreign('masterUserId')
->references('id')
->on('users');
$table->foreign('package_type')
->references('id')
->on('packages');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('apps');
}
}
My database migrations for the tenant,
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTenantsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(): void
{
Schema::create('tenants', function (Blueprint $table) {
$table->string('id', 36)->primary(); // 36 characters is the default uuid length
// (optional) your custom, indexed columns may go here
$table->json('data');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(): void
{
Schema::dropIfExists('tenants');
}
}
And domains,
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDomainsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up(): void
{
Schema::create('domains', function (Blueprint $table) {
$table->string('domain', 255)->primary();
$table->string('tenant_id', 36);
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(): void
{
Schema::dropIfExists('domains');
}
}
I have included all the required imports for multi tenant. But When ever I try to run my store method and create new record I'm getting
ErrorException
Trying to get property 'tenant_id' of non-object
error and tenant db or record in app table not get created.

Laravel Factory | The mapping is not specified

I'm trying to create some mock data using faker for a Model called Product to test Scout & ElasticSearch but unfortunately, I'm getting an error. When I use factory(App\Product::class, 200)->create() inside of php artisan tinker to generate the data, I get the following error: LogicException with message 'Nothing to update: the mapping is not specified.' Any pointers on which other files I should look at
App > Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use ScoutElastic\Searchable;
class Product extends Model {
use Searchable;
protected $indexConfigurator = ProductIndexConfigurator::class;
protected $fillable = ['sku', 'name', 'type', 'price', 'upc', 'category', 'shipping'
, 'description', 'manufacturer', 'model', 'url', 'image'];
public function products ()
{
return $this->belongsTo('App\Product');
}
}
ProductFactory.php
<?php
$factory->define(App\Product::class, function (Faker\Generator $faker) {
return [
'sku' => $faker->randomDigit,
'name' => $faker->name,
'type' => $faker->name,
'price' => $faker->randomDigit,
'upc' => $faker->randomDigit,
'category' => $faker->name,
'shipping' => $faker->randomDigit,
'description' => $faker->name,
'manufacturer' => $faker->name,
'model' => $faker->name,
'url' => $faker->url,
'image' => $faker->url,
];
});
Migration - create_products_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('product', function(Blueprint $table) {
$table->increments('id');
$table->string('sku');
$table->string('name');
$table->string('type');
$table->string('price');
$table->string('upc');
$table->string('category');
$table->string('shipping');
$table->string('description');
$table->string('manufacturer');
$table->string('model');
$table->string('url');
$table->string('image');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('product');
}
}
Your code is OK and works for me, you're just missing the properties $table and $timestamps on your Product model:
class Product extends Model
{
public $table = 'product';
public $timestamps = false;

ErrorException array to string conversion on migrate --seed

I'm trying to set up my very first laravel project however when I try to have artisan to seed the database with faker it throws
[errorException] array to string conversion
I'm just working with the stock users migration file
and using the command php artisan migrate --seed
Any guidance would be greatly appreciated
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('role', array('user', 'admin', 'superuser'));
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
and this UserTableSeeder that artisan generated for me
use Illuminate\Database\Seeder;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\User::class, 49)->create();
factory(App\User::class)->create([
'name' => 'admin',
'role' => 'admin',
]);
}
}
this is my Modelfactory.php
$factory->define(App\User::class, function ($faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
'role' => $faker->word->randomElement(array('user','superuser')),
];
});
$table->string('role', array('user', 'admin', 'superuser'));
You are selecting a type of string and then providing an array.
This is exactly what your error is talking about.
Your error is because of this line
$table->string('role', array('user', 'admin', 'superuser'));
change string to enum; ex:
$table->enum('role', array('user', 'admin', 'superuser'));
this will execute.
You say string but provide an array in this line:
$table->string('role', array('user', 'admin', 'superuser'));
You should use :
$table->enum('role', ['user', 'admin', 'superuser']);
For reference see here:
https://laravel.com/docs/5.8/migrations#creating-columns

Laravel 4 seed returns successful but nothing in database

I'm working with Laravel 4 and trying to seed the database with some users. I'm using the Zizaco Confide plugin, so my User model extends ConfideUser instead of Eloquent per the documentation. I added a few fields to the model also, but nothing super complicated. I have tried removing those fields but I get the same issue.
I created a UserSeeder class that I call with the DatabaseSeeder and then run php artisan migrate:refresh --seed. It runs without error and returns "The database has been seeded", and that is true for every table except users. No users ever get inserted. I've tried creating the user with User::create(array(...)) as well as $user = new User ... $user->save() and I get the same results. No errors are dumped, and nothing is in any log I can find on the system. If I insert some var_dumps in the UserSeeder->run() method, I see that the objects are created with the correct values, but nothing saves.
What am I missing? Here's some code samples, I can provide more if needed:
models\User.php:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Zizaco\Confide\ConfideUser;
//class User extends Eloquent implements UserInterface, RemindableInterface {
class User extends ConfideUser
{
// for Entrust
use \Zizaco\Entrust\HasRole;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function agency()
{
if ($this->agency_type == 'local')
{
return $this->hasOne('Local');
}
if ($this->agency_type == 'county')
{
return $this->hasOne('County');
}
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
database\migrations\xxxxxxxxx_confide_setup_users_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
class ConfideSetupUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
// Creates the users table
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->string('confirmation_code');
$table->boolean('confirmed')->default(false);
$table->string('address1');
$table->string('address2')->nullable();
$table->string('state', 2);
$table->string('zipcode', 9);
$table->string('phone', 10);
$table->string('extension',5 )->nullable();
$table->string('fax', 10)->nullable();
$table->enum('agency_type', array('local', 'county', 'state'))->default('local');
$table->integer('agency')->unsigned()->nullable();
$table->dateTime('last_seen');
$table->timestamps();
$table->softDeletes();
});
// Creates password reminders table
Schema::create('password_reminders', function($t)
{
$t->string('email');
$t->string('token');
$t->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('password_reminders');
Schema::drop('users');
}
}
database\seeds\UserSeeder.php:
<?php
use \Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(
array(
'username' => 'local_test',
'email' => 'nathan#abc.com',
'password' => Hash::make('local'),
'confirmation_code' => '483JU3ID8',
'confirmed' => true,
'address1' => '123 Main St.',
'state' => 'MI',
'zipcode' => '12345',
'phone' => '5559993436',
'agency_type' => 'local',
'agency' => null,
'last_seen' => new DateTime
)
);
Do this in your user seeder class:
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->truncate();
$users = array(
array( 'username' => 'local_test',
'email' => 'nathan#abc.com',
'password' => Hash::make('local'),
'confirmation_code' => '483JU3ID8',
'confirmed' => true,
'address1' => '123 Main St.',
'state' => 'MI',
'zipcode' => '12345',
'phone' => '5559993436',
'agency_type' => 'local',
'agency' => null,
'last_seen' => new DateTime
)
);
// make sure you do the insert
DB::table('users')->insert($users);
}
}
and then, make sure you invoke it in your DatabaseSeeder.php file
<?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call('UsersTableSeeder');
}
}
Confide uses Ardent for validation. adding 'password_confirmation' property is required. Also you don't need to Hash::make since Confide will also handle that for you.
<?php
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->truncate();
$users = array(
array( 'username' => 'local_test',
'email' => 'nathan#abc.com',
'password' => 'local',
'password_confirmation' => 'local',
'confirmation_code' => '483JU3ID8',
'confirmed' => true,
'address1' => '123 Main St.',
'state' => 'MI',
'zipcode' => '12345',
'phone' => '5559993436',
'agency_type' => 'local',
'agency' => null,
'last_seen' => new DateTime
)
);
// make sure you do the insert
DB::table('users')->insert($users);
}
}
I found that the seeder fails silently.
I was seeing a user table. The return was a seed success but it was empty.
I followed the answer above using the insert method.
When doing the above method, an error was returned saying that a column did not have a default value in the database table.
I adjusted the column and reverted back to the create method from the laravel doc.
It was then successful.
So in my instance the there was a database error but it failed without telling me.
With the insert method I was able to find the error.
Then the create method worked once there were no errors.

Categories