I'm creating an Add-User function in my website (Laravel 5.1), in which an admin account can create an account using an email, and the password will be sent to that email. The form in the Add-User view asks for the name, email, permission level, and description.
The create function supposed to accept a request from that wiew, generate a password, add the password and the creator's ID into the request, create a DB entry based on the request, then send an email to that address. I'm currently stuck at creating the DB based on the request. Here is my function :
public function create(Request $request)
{
//generate password
$pass = str_random(10);
$passcrypt = bcrypt($pass);
$email = $request->input('email');
//change the fillable in the model
$user = new User;
$user->changeFillableMode("CREATE");
//validation
$this->validate($request,['fullname'=>'required',
'email'=>'required|email',
'permission_id'=>'required']);
//adding new items to request array
$input = $request->all();
$input = array_add($input,'created_by_user_id',Auth::user()->user_id);
$input = array_add($input,'password',$passcrypt);
$user->create($input);
//send mail
$data['email'] = $request->input('email');
$data['pass'] = $pass;
Mail::queue('mail.mailbodycreate', $data, function($message) use ($email)
{
$message->to($email)->subject('Account info');
});
}
The $input already shows that the password and creator Id are already in the array, but I keep getting error that it's not in the array (since password is not nullable in my migration). can anyone help?
update : I add dd($input); after the last array_add. this is the result
array:7 [
"_token" => "9VowN9ICgkAb9cegbbQzhFtfIhmQr0DqlGj724bN"
"fullname" => "Aldi"
"email" => "aldi#gmail.com"
"permission_id" => "1"
"description" => "testing add user"
"created_by_user_id" => 4
"password" => "$2y$10$Dc4TZqMYE1kyPc7wFHBT1.8KUzk35QqV32wKegstjMFHnD/rhjsw6"
]
update 2 : here is the model for the User table :
protected $table = 'msuser';
protected $primaryKey = 'user_id';
protected $fillable = ['fullname', 'email', 'description','permission_id'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['deleted_at'];
public function changeFillableMode($mode){
switch($mode){
case "CREATE" :
$this->fillable = ['fullname', 'email', 'password', 'description','permission_id','created_by_user_id','has_change_password'];
break;
}
}
the changeFillableMode is used to change the content of $fillable in the controller function.
I prefer to add key-value pairs in PHP this way:
//adding new items to request array
$input = $request->all();
$input['created_by_user_id'] = Auth::user()->user_id;
$input['password'] = $passcrypt;
ensure that protected $fillable contains all required keys before create
use constants for switch:
const CREATE = 'create';
public function changeFillableMode($mode){
switch($mode){
case self::CREATE:
$this->fillable = ['fullname', 'email', 'password', 'description','permission_id','created_by_user_id','has_change_password'];
break;
}
}
and call it:
$user->changeFillableMode(User::CREATE);
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 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');
}
I have a function in my laravel controller for login to a website, and I'm having trouble figuring out the best way to pass the two fields (email, and password)
into a function call loginAttempt()
Currently I have:
public function login(Request $request)
{
//getting email and password form fields for validation
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
//Need to pass email and password into the loginAttempt() function
$authService = new AuthService();
$login = $authService->loginAttempt();
dd($login);
}
I know I can use $login = $authService->loginAttempt($arguments); but the function I'm passing into needs the email and password as separate variables.
How can I pass them both into that loginAttempt() function call?
Just grab the values from the input using $request->input as shown below
public function login(Request $request)
{
//getting email and password form fields for validation
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
//Need to pass email and password into the loginAttempt() function
$email = $request->input ('email');
$password = $request->input ('password');
$authService = new AuthService();
$login = $authService->loginAttempt($email, $password);
dd($login);
}
you can mulitple variable two ways function to function
first way
passing each variable as separated
$authService = new AuthService();
$login = $authService->loginAttempt($request->email, $request->password);
second way
create a single dimension array used like that
$authService = new AuthService();
$login = $authService->loginAttempt(['email' => $request->email, 'password' => $request->password]);
and in your AuthService getting value by using key like that
$data['email'] or $data['password']
I am using Socialite to login/register with facebook into my application. When I dump my $facebookUser variable I see this json :
$facebookuser :
But when I try to store the id and avatar , it doesn't store it and I can't display the users profile picture of facebook. I am using laravel to store my user.
AuthController.php :
public function handleProviderCallback()
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
return redirect('auth/facebook');
}
$authUser = $this->findOrCreateUser($user);
Auth::login($authUser, true);
return redirect()->route('home')->with('successfullFacebookLogin', Auth::user()->name);
}
private function findOrCreateUser($facebookUser)
{
// When I dd($facebookuser) it gives json stated above
$authUser = User::where('facebook_id', $facebookUser->id)->first();
if ($authUser){
return $authUser;
}
return User::create([
'name' => $facebookUser->name,
'email' => $facebookUser->email,
'facebook_id' => $facebookUser->user['id'],
'avatar' => $facebookUser->avatar,
'facebookAccount' => 1
]);
}
Use Laravel Socialite provided methods to access user details rather than access the property directly, here is list of available methods for all built-in providers:
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();
So your code should be:
private function findOrCreateUser($facebookUser)
{
// When I dd($facebookuser) it gives json stated above
$authUser = User::where('facebook_id', $facebookUser->id)->first();
if ($authUser){
return $authUser;
}
return User::create([
'name' => $facebookUser->getName(),
'email' => $facebookUser->getEmail(),
'facebook_id' => $facebookUser->getId(),
'avatar' => $facebookUser->getAvatar(),
'facebookAccount' => 1
]);
}
Don't forget to state those columns above in $fillable property of User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'facebook_id', 'avatar', 'facebookAccount'
];
Otherwise fill the attributes manually:
$user = new User;
$user->name = $facebookUser->getName();
$user->email = $facebookUser-> getEmail();
$user->facebook_id = $facebookUser->getId();
$user->facebookAccount = 1;
$user->save();
return $user;
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.