Usually we create a database seed file like this to seed a database table:
class UsersSeeder extends DatabaseSeeder {
public function run()
{
$users = [
[
'email' => 'mymail#mail.com',
'password' => Hash::make('123456'),
'name' => 'Admin'
]
];
foreach ($users as $user) {
User::create($user);
}
}
}
But how can we seed table with relationship? For example, table users with table memberdetail:
Users Table:
id, email, password, name
memberdetail table:
id, userid, gender, address, dob
memberdetail table's userid column will show the id which links to the id on users table. How can we seed these 2 tables?
Thank you.
Assume you have a model called MemberDetail.
class UsersSeeder extends DatabaseSeeder {
public function run()
{
$users = [
[
'email' => 'mymail#mail.com',
'password' => Hash::make('123456'),
'name' => 'Admin'
]
];
foreach ($users as $user) {
$user = User::create($user);
$memberDetail = new MemberDetail;
$memberDetail->userid = $user->id;
// Fill up gender, address, dob
// i am not sure what data you have for gender, address and dob.
$memberDetail->gender = 'Male';
$memberDetail->address = 'Australia';
$memberDetail->dob = '2014-01-08';
$memberDetail->save();
}
}
}
Related
In the admin panel, I have something called Group that an admin can make a group of users so my scheme is:
groups table contains:
id
name
1
group1
group_user table contains:
id
group_id
user_id
1
1
2
2
1
3
My logic is: if a user belongs to a group, that user cannot be added again to the same group:
In update, when I add a user that already exists in group, it added it again:
public function update($id, Request $request)
{
$request->validate([
'name' => 'sometimes|nullable|string',
'user_ids' => 'sometimes|array',
]);
$group = Group::findOrFail($id);
$group->update($request->only('name'));
if ($ids = $request->user_ids) {
$group->users()->attach($ids);
}
return $this->apiRespone(null, 'group updated successfully', null, 200);
}
Just check if user already is in the group before attaching to it:
public function update($id, Request $request)
{
$request->validate([
'name' => 'sometimes|nullable|string',
'user_ids' => 'sometimes|array',
]);
$group = Group::findOrFail($id);
$group->update($request->only('name'));
foreach($request->user_ids as $user_id) {
if (!$group->users()->where('id', $user_id)->exists()) {
$group->users()->attach($user_id);
}
}
return $this->apiRespone(null, 'group updated successfully', null, 200);
}
Update:
To get the list of already existing members, apply this in your loop logic:
$existingUsers = [];
foreach($request->user_ids as $user_id) {
if (!$group->users()->where('id', $user_id)->exists()) {
$group->users()->attach($user_id);
} else {
$existingUsers[] = $user_id;
}
}
// now you can use $existingUsers
I have a register controller (provided by Laravel) and I have two different registration forms (Customer and Dealer) and they both use the same controller. The difference between the two forms is that certain input fields are in one form but not the other. So my code works fine but I added three new fields (three new columns as well) to my dealer form and it's not making an insert to occupation, date of birth,gender, and ethnicity columns when I registered it.
My RegisterController.php:
protected function create(array $data)
{
$user = User::create([
// Users table
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
$user->userInfo()->create([
'name' => $data['name'],
'NRIC' => $data['nric'], // Create NRIC field.
]);
$user->userAddresses()->create([
'address_1' => $data['homeaddress1'],
'address_2' => $data['homeaddress2'],
'address_3' => $data['homeaddress3'],
'zipcode' => $data['postcode'],
]);
$user->userContacts()->create([
'mobile_num' => $data['number'],
'emergency_num' => $data['emergency']
]);
// check if dealer form is registered, assign dealer role or otherwise
if ($data['RegistrationForm'] == 2) {
//assign track id code to dealer
$user->track_id = 1911000000 + $user->user_id;
$user->userInfo()->occupation = $data['occupation'];
$user->userInfo()->ethnicity = $data['race'];
$user->userInfo()->date_of_birth = $data['dob'];
$user->userInfo()->gender = $data['gender'];
$user->save();
$user->assignRole('1');
$user->assignRole('2');
} else {
//assign track id code to customer
$user->track_id = 1913000000 + $user->user_id;
$user->userAddresses()->shipping_address = $data['shippingaddress'];
$user->save();
$user->assignRole('1');
}
return $user;
}
}
I checked my models and they seemed fine.
UserInfo model:
class UserInfo extends Model
{
// Set table
protected $table = 'user_infos';
// Set timestamps
public $timestamps = true;
// Set primary key
protected $primaryKey = 'user_id';
// Set mass assignable columns
protected $fillable = [
'name',
'NRIC',
'dealer_id',
'ethnicity',
'gender',
'date_of_birth',
'occupation'
];
/**
* Get the user info associated with the user.
*/
public function user()
{
return $this->belongsTo('App\Models\Users\User', 'user_id');
}
}
track_id and assignRole inserts fine but not those new columns I added.
Did I make any mistake here?
The values are not getting saved because you are not saving Userinfo properly.
Do following
if ($data['RegistrationForm'] == 2) {
//assign track id code to dealer
$user->track_id = 1911000000 + $user->user_id;
$user->save();
$userinfo = $user->userInfo;
$userinfo->occupation = $data['occupation'];
$userinfo->ethnicity = $data['race'];
$userinfo->date_of_birth = $data['dob'];
$userinfo->gender = $data['gender'];
$userinfo->save();
$user->assignRole('1');
$user->assignRole('2');
} else {
//assign track id code to customer
$user->track_id = 1913000000 + $user->user_id;
$user->userAddresses()->shipping_address = $data['shippingaddress'];
$user->save();
$user->assignRole('1');
}
User model is returning id=null, while debug I found out the the reason behind this issue is that in my User model I override the $primary_key with a custom one
User Model
class User extends Authenticatable
{
use Notifiable;
// Set the primary key to the generated version instead of the regular ID
protected $primaryKey = 'user_code';
// Set the key type
protected $keyType = 'string';
// Diable the auto-increment option
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_code',
'fname',
'mname',
'lname',
'email',
'dob',
'age',
'gender',
'insurance_number',
'ssn',
'avatar',
'is_active',
'userable_id',
'userable_type',
];
}
I have the following code that generate a new user_code that uses the id
$user = new User;
$user = $user->create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
Users Migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('user_code')->unique()->nullable();
$table->string('fname')->default('tbd');
$table->string('mname')->default('tbd');
$table->string('lname')->default('tbd');
$table->string('email')->unique()->nullable();
$table->date('dob')->default('1000-01-01');
$table->integer('age')->default(0);
$table->string('gender')->default('tbd');
$table->integer('insurance_number')->default(0);
$table->integer('ssn')->default(0);
$table->string('avatar')->default('tbd');
$table->boolean('is_active')->default(false);
$table->string('userable_code')->default('tbd');
$table->string('userable_type')->default('tbd');
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
$user->id is returning null, why such behavior is happening?
You've set $user as a new model instance:
$user = new User;
But then you're trying to create a new user from that instance, that won't work:
$user = $user->create([ ...
Since that doesn't work, you're not really saving anything to the DB, and you won't get an ID.
The second part of your problem is (as #TimLewis pointed out in the comments) that you are trying to create and save a model with a blank primary key (user_code). That won't work, so you'll need to work out what the ID is before trying to save it.
// Remove this line:
// $user = new User;
// Find the current highest ID:
$last = User::max('id');
// Your new user will have this ID
$newID = $last->id + 1;
// And just use the normal way to create and save a model:
$user = User::create([
'userCode' => "ur" . date('y') . date('m') . $newID,
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
I may not know what you are trying to achieve here, but I'm just assuming that this is a very special use case.
Try this:
// Notice how we are using the User as a class, not instantiating it.
$user = User::create([
'fname' => $request->fname,
'lname' => $request->lname,
'email' => $request->email,
]);
// Save the user in the DB
// Generate a usercode for the newely created user
$userCode = "ur" . date('y') . date('m') . $user->id;
This assumes that your id column in your database table is still INCREMENTS and PRIMARY KEY
I am relatively new to laravel and have a project that requires a bit of manual configuration.
Background:
Working with Authentication Scaffolding (handles the user
registration and login)
I have two tables: Profile and Users.
All Users have one Profile.
But not all Profiles have a user.
Setup:
Profile table => id, name, avatar, etc.
User Table => profile_id, email, password
Since the Laravel Auth (Scaffold) handles the Registration and Login. I am trying to save data into the Profile table before saving the user table.
protected function create(array $data)
{
$profile = Profile::create
([
'slug' => $data['name'],
'name' => $data['name'],
]);
$user = User::create
([
'profile_id' => $profile->id,
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return $user;
}
But this is not working. And the error message is telling me there is no profile_id assigned in the query.
What am I doing wrong?
How are your models set up? If Eloquent and your DB is set up correctly you can do this:
$profile = new Profile;
$profile->slug = $data['name'];
$profile->name = $data['name'];
$profile->save();
// At this point now you'll be able to get an ID of the profile
$user = new User;
$user->profile_id = $profile->id;
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->save();
return $user;
I am trying to register a user using User model and calling the create() method and passing array of inputs but getting Column not found: 1054.
public function postRegister(RegisterRequest $request)
{
$user = User::create([
'email' => $request->input('register-email'),
'password' => $request->input('register-password'),
'lastname' => $request->input('register-lastname'),
'firstname' => $request->input('register-firstname'),
]);
}
The keys inside the create() method is my database email, password, lastname, firstname and I added 'register-' in my html inputs because I have another form that use the name 'email and password'
so you can use the create method with array as a parameter, you must declare the columns in the fillable parameter
see: http://laravel.com/docs/5.1/eloquent#mass-assignment
you can also do it this way
$user = new User;
$user->email = $request->input('register-email');
$user->password = $request->input('register-password');
$user->lastname = $request->input('register-lastname');
$user->firstname = $request->input('register-firstname');
$user->save();