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');
}
Related
My need create new user in admin dashboard, this store function, but database saving string not hash, please help.
When I output via dd(), then the hash working
`
public function store(Request $request)
{
$data = $request->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:8|confirmed'
]);
$object = new Specialist();
$object->groups = 3;
$object->password = \Hash::make($data['password']);
$object->fill(request()->all());
$object->save();
return redirect()->route('specialists.index');
}
`
Model
`class Specialist extends Model
{
// USE DATABASE TABLE users
protected $table = 'users';
// FILL COLUMNS...
protected $fillable = ['email', 'password', 'name'];
}`
$object->fill(request()->all());
This line is overwriting the password field because request()->all() includes password.
Use except() method to remove the fields that you don't need:
$object->password = \Hash::make($data['password']);
$object->fill(request()->except('password'));
I'm currently working on a project that has an accounts management section where the system admin creates the user accounts.
The [Users] table has a column named "Organization_name", which is the user's represented organization. After submitting the form, "Organization_name" will then be also added to the [Organization] table, under the [name] field. The two tables are related by the "user_id" column (taken from the "id" column of the [Users]).
I managed to create a working code to add a [Users] account that also adds the organization_name to the [Organization] table, although now I'm wondering how can I make a function that will also edit the rows in the [Organization] table whenever I edit the fields in [User].
(ex. I changed the "organization_name" field in [Users] with id=1 from "Organization A" to "Organization B," the "name" field in [Organization] with user_id=1 should also change from "Organization A" to "Organization B" too).
NOTE: "role_id" determines what kind of account permissions a user account will have, it doesn't affect the question but I'll leave it in the code snippet below just in case.
I'll attach the codes that I used below:
UserController.php
private static function createUser(Request $request)
{
$user = new User();
$user->email = $request->get('email');
$user->organization_name = $request->get('organization_name');
$user->password = Hash::make($request->get('password'));
$user->role_id = $request->get('role_id');
return $user;
}
private static function createSubUser(Request $request, $user_id)
{
$role_id = $request->get('role_id');
if($role_id == 1)
{
$sub_user = new Organization();
$sub_user->user_id = $user_id;
$sub_user->name = $request->get('organization_name');
}
elseif($role_id == 2)
{
$sub_user = new Staff();
$sub_user->user_id = $user_id;
}
elseif($role_id == 3)
{
$sub_user = new Administrator();
$sub_user->user_id = $user_id;
}
return $sub_user;
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|string|email|max:255|unique:users',
'organization_name' => 'required|string|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = static::createUser($request);
$user->save();
$sub_user = static::createSubUser($request, $user->id);
$sub_user->save();
}
public function updateUserInfo(Request $request)
{
$user = User::find($request->id);
if($user->email == $request->email){
$check_email = false;
}
else{
$check_user = User::where('email', $request->email)->first();
if (!empty($check_user)) {
$check_email = true;
}
else {
$check_email = false;
}
}
if($check_email === true)
{
return response()->json([
'success' => false,
'error' => "User with the registered email of {$request->input('email')} already exists",
]);
}
else
{
$user = User::where('id', $request->id)->update([
'email' => $request->input('email'),
'organization_name' => $request->input('organization_name'),
'role_id' => $request->input('role_id')
]);
return response()->json([
'success' => true,
'user' => $user
]);
}
}
Thank you!
Why you need to add user_id on organization??
An organzation should have many students or users.No need to store organization_name on users table just save the id of organization.When you need to update organization name just update it on organization table.Because you don't need to change in user table you just save here id. Feel free to comment if you have any confussion.
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'm following this Laravel login/register tutorial on YouTube and I ran into a problem.
It seems I cannot insert the data from the $user object into my database.
Everything I have so far works perfectly fine until I reach the $user->save() method.
The following is my AccountController.php. You'll notice that I'm using print_r to try and debug the process. The first print_r gets printed to my page, but the second never does: Laravel just stops and outputs a cryptic Whoops, looks like something went wrong. warning.
class AccountController extends BaseController {
public function getCreate()
{
return View::make('account.create');
}
public function postCreate()
{
$validator = Validator::make(Input::all(), array(
'email' => 'required|max:64|min:3|email|unique:users',
'name' => 'required|max:64|min:3',
'password' => 'required|max:64|min:6'
));
if ($validator->fails())
{
// Return to form page with proper error messages
return Redirect::route('account-create')
->withErrors($validator)
->withInput();
}
else
{
// Create an acount
$email = Input::get('email');
$name = Input::get('name');
$password = Input::get('password');
// Activation code
$code = str_random(64);
$user = User::create(array(
'active' => 0,
'email' => $email,
'username' => $name,
'password' => Hash::make($password),
'code' => $code
));
if ($user)
{
// Send the activation link
Mail::send('emails.auth.activate', array(
'link' => URL::route('account-activate', $code),
'name' => $name
), function($message) use($user) {
$message
->to($user->email, $user->username)
->subject('Jasl | Activate your new account');
});
return Redirect::route('home')
->with('success', 'One more step! You\'ll get an email from us soon. Please follow the activation link to activate your account.');
}
}
}
public function getActivate($code)
{
// Find user whose code corresponds to the one we've previously sent through email
$user = User::where('code', '=', $code)->where('active', '=', 0);
if ($user->count())
{
$user = $user->first();
$user->active = 1;
$user->code = '';
echo '<pre>', print_r($user), '<pre>';
if ($user->save())
{
echo '-----------------------';
echo '<pre>', print_r($user), '<pre>';
}
}
}
}
I've googled a bit and found out that I should create a $fillable array in my User class, so I did it:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('active', 'name', 'email', 'password', 'password_temp', 'code', 'salt', 'created_at', 'updated_at', 'pref_weight', 'pref_units', 'pref_time', 'pref_ener');
use UserTrait,
RemindableTrait;
/**
* 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', 'remember_token');
}
Those are actually all the elements that my users table has.
This did not solve the problem.
What am I missing? Why isn't $user->save() working properly?
I got it.
My problem was that I created the id column of my users table with a custom name, user_id, instead of simply id. Apparently Laravel does not like this at all. The debugger pointed me to:
C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Connection.php
with the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update users set active = 1, code = , updated_at = 2015-01-20 21:28:14 where id is null)
I didn't know you shouldn't customize id columns. Renaming it solved the problem entirely and the database now updates correctly.
Thanks #patricus for the useful debugging tip, that's what allowed me to track this error down.
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();
}
}
}