How to create new user in Laravel? - php

I created the model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ClientModel extends Eloquent implements UserInterface, RemindableInterface {
protected $connection = 'local_db';
protected $table = 'administrators';
protected $fillable = ['user_id'];
public function getAuthIdentifier()
{
return $this->username;
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getReminderEmail()
{
return $this->email;
}
}
When I try to use it like this:
ClientModel::create(array(
'username' => 'first_user',
'password' => Hash::make('123456'),
'email' => 'my#email.com'
));
It creates empty entry in DB...

I think you make it too complicated. There is no need to make it this way. By default you have User model created and you should be able simple to create user this way:
$user = new User();
$user->username = 'something';
$user->password = Hash::make('userpassword');
$user->email = 'useremail#something.com';
$user->save();
Maybe you wanted to achieve something more but I don't understand what you use so many methods here if you don't modify input or output here.

You are using create method (Mass Assignment) so it's not working because you have this:
// Only user_id is allowed to insert by create method
protected $fillable = ['user_id'];
Put this in your model instead of $fillable:
// Allow any field to be inserted
protected $guarded = [];
Also you may use the alternative:
protected $fillable = ['username', 'password', 'email'];
Read more about Mass Assignment on Laravel website. While this may solve the issue but be aware of it. You may use this approach instead:
$user = new User;
$user->username = 'jhondoe';
// Set other fields ...
$user->save();

Nowadays way :
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
or even:
$arrLcl = [];
$arrLcl['name'] = $data['name'];
$arrLcl['email'] = $data['email'];
$arrLcl['password'] = $data['password'];
User::create($arrLcl);

Related

Codeigniter 4 ignoring model insert callback

Running model->insert() from my controller does not trigger the beforeInsert function, below is my model and the function from my conntroller
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model {
protected $table = 'admin_users';
protected $useAutoIncrement = true;
protected $primaryKey = 'row_uid';
protected $returnType = 'object';
protected $beforeInsert = ['passwordHash'];
protected $allowCallbacks = true;
protected $allowedFields = ['id', 'row_uid', 'username', 'email', 'password', 'active', 'deleted_at'];
public function __construct() {
return $this;
}
protected function passwordHash($data) {
$data['data']['row_uid'] = uniqid('',true);
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
if(isset($data['data']['password_c'])) unset($data['data']['password_c']);
return $data;
}
}
And here is the controller function
public function postRegister() {
$request = \Config\Services::request();
if($post = $request->getPost()) {
$valid = $this->validate([
'username' => 'is_unique[admin_users.username]', // Change table name to be dynamic
'email' => 'required|valid_email|is_unique[admin_users.email]', // Change table name to be dynamic
'password' => 'required|min_length[10]|max_length[100]',
'password_c' => 'required|matches[password]',
]);
if(!$valid) {
$this->data['errors'] = $this->validator->getErrors();
foreach($post as $key => $e) {
if(isset($this->data['errors'][$key])) {
$this->data['invalid_fields'][$key] = ' is-invalid';
} else $this->data['invalid_fields'][$key] = '';
}
return $this->getRegister();
}
$l = $this->userModel->insert($post);
echo '<pre>',var_dump($l),'</pre>';exit;
}
}
I determine that the callback is not running because the password is not hashed, the uid is not generated and running die or exit does nothing.
Thank you
EDIT:
I got it working by adding allowCallback() but i shouldn't need this?
$this->userModel->allowCallbacks(true)->insert($post);
1 - Delete the constructor method in the model; you don't need that .
2- set protected $allowCallbacks = true; before $beforeInsert = ['passwordHash'];
The above approach is standard coding in the Codeigniter framework. If those steps didnt resolve the problem, the solution is to check the database for the row_uid and password types.

How to store bcrypt data using Make request in laravel

This is how I would make such a function
Controller code
public function store(RegistrationStoreRequest $request){
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
This is my Request form code
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
];
}
You have two options:
Create a value mutator:
public function setPasswordAttribute($value) {
$this->attributes['password'] = Hash::make($value);
}
however you need to ensure you never prehash the password.
Hash in controller
public function store(RegistrationStoreRequest $request){
$user = User::create(array_merge(Arr::except($request->validated(), 'password'), [ 'password' => Hash::make($request->password) ]));
Auth::login($user);
return redirect()->home();
}
The easiest and most clean way is to use a custom cast for password field, first create UserPasswordCast.php class:
<?php
//app/Casts/UserPasswordCast.php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Facades\Hash;
class UserPasswordCast implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return $value;
}
public function set($model, $key, $value, $attributes)
{
//return hashed value
return Hash::make($value);
}
}
Suggested location:
app/Casts/UserPasswordCast.php
Then update your 'user' model to use this cast, add "$casts" array or update it if existed:
use App\Casts\UserPasswordCast;
...
protected $casts = [
...
'password' => UserPasswordCast::class
];
That's it, you don't have to worry about password again
Just save your user model as it:
public function store(RegistrationStoreRequest $request)
{
$user = User::create($request->validated());
Auth::login($user);
return redirect()->home();
}
For more info please check:
https://laravel.com/docs/8.x/eloquent-mutators#custom-casts
=>create method function add in User.php(Model).
public static function create($user, $request)
{
if (isset($request->name)) {
$user->name = $request->name;
}
if (isset($request->email)) {
$user->email = $request->email;
}
if (isset($request->password)) {
$user->password = bcrypt($request->password);
}
if (isset($request->confirmpassword)) {
$user->confirmpassword = $request->confirmpassword;
}
$user->save();
return $user;
}
=>New user create with validate your all request field.
public function store(RegistrationStoreRequest $request){
$user = User::create(New User,$request);
Auth::login($user);
return redirect()->home();
}
Please try this code it is working.

Laravel manual auth - Never works

I am trying to make Auth for an API Rest manually, but the response for Auth::attempt is always false.
Route
Route::group(["prefix"=>"api"], function(){
Route::post('/login', [
'as' => 'checkLogin',
'uses' => 'LoginCtrl#checkLogin'
]);
});
Controller
class LoginCtrl extends Controller
{
public function checkLogin(Request $request){
$input = $request->all();
if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
$data = ["response"=>true,"access_token"=>"test"];
}else{
$data = ["response"=>false,"access_token"=>"none"];
}
return response()->json($data);
}
}
I have userd Hash::make to encrypt the password on the user creation.
My model is:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = "usuarios";
protected $username = 'username';
protected $fillable = [
'name', 'username', 'password'
];
protected $hidden = [
//'password', 'remember_token',
];
public $timestamps = false;
public function access_token(){
return $this->hasOne('App\AccessToken');
}
}
What am I doing wrong?
EDIT
$user = new User();
$user->username = "myFreshUsername";
$user->password = Hash::make('userPwd');
$user->save();
Thats my user creation. If this helps I didn't launch `php artisan make:auth', may this order be necessary?
of course it always false because you did not use correct way to get the json in your request using laravel
the correct way is
$input = $request->json()->all();
not
$input = $request->all();
so your controller would be like this
class LoginCtrl extends Controller
{
public function checkLogin(Request $request){
$input = $request->json()->all();
if(Auth::attempt(['username' => $input['user'], 'password' => $input['password']])){
$data = ["response"=>true,"access_token"=>"test"];
}else{
$data = ["response"=>false,"access_token"=>"none"];
}
return response()->json($data);
}
}

Save object with foreign keys in laravel

I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...
When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.

Ambiguous class resolution in laravel phpexcel update

I try to update the laravel with php excel while installing i found the below warning in the composer.
Error:
Warning: Ambiguous class resolution, "SettingsController" was found in both
"C:\xampp\htdocs\mti\app\controllers\SettingsController.php" and
"C:\xampp\htdocs\mti\app\controllers\SettingsControllerBackup.php", the first
will be used.Warning: Ambiguous class resolution, "ClassModel" was found in both
"C:\xampp\htdocs\mti\app\models\ClassModel.php" and "C:\xampp\htdocs\mti\
app\models\LoginModel.php", the first will be used.
SettingsController:
<?php
class SettingsController extends BaseController
{
public function ChangePasswordLayout()
{
return View::make('settings/changepassword/changepassword');
}
public function ChangePasswordProcess()
{
$PasswordData = Input::all();
Validator::extend('pwdvalidation', function($field, $value, $parameters)
{
return Hash::check($value, Auth::user()->password);
});
$messages = array('pwdvalidation' => 'The Old Password is Incorrect');
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes())
{
$user = User::find(Auth::user()->id);
$user->password = Hash::make(Input::get('NewPassword'));
$user->save();
return Redirect::to('changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else
{
return Redirect::to('changepassword')->withInput()->withErrors($validator);
}
}
public function ProfileLayout()
{
$user = Auth::user()->id;
$ProfileDetailsbyid = ProfileModel::where('id', $user)->get()->toArray();
return View::make('settings/profile/profile')->with('ProfileDetailsbyid', $ProfileDetailsbyid);
}
public function ProfileUpdateProcess($data=NULL)
{
$user = Auth::user()->id;
$ProfileDetailsbyid = ProfileModel::where('id', $user)->get()->toArray();
$ProfileData = array_filter(Input::except(array('_token')));
$validation = Validator::make($ProfileData, ProfileModel::$rules);
if ($validation->passes())
{
if(!empty($ProfileData['Photo']))
{
Input::file('Photo')->move('assets/uploads/profilephoto/', $user . '-Photo.' . Input::file('Photo')->getClientOriginalName());
$Photo=$user.'-Photo.' . Input::file('Photo')->getClientOriginalName();
unset($ProfileData['Photo']);
$ProfileData['Photo']=$Photo;
}
$affectedRows = ProfileModel::where('id', $user)->update($ProfileData);
//VehicleModel::create($VehicleData);
return Redirect::to('profile')->with('Message', 'Profile Details Update Succesfully')->with('ProfileDetailsbyid', $ProfileDetailsbyid);
} else
{
return Redirect::to('profile')->withInput()->withErrors($validation->messages())->with('ProfileDetailsbyid', $ProfileDetailsbyid);
}
}
}
ClassModel:
<?php
class ClassModel extends Eloquent
{
protected $primaryKey = 'AutoID';
protected $created_at = 'CreatedAt';
protected $updated_at = 'UpdatedAt';
protected $table = 'class';
protected $guarded = array('GradeName');
protected $fillable = array('GradeName');
public function batch(){
return $this->hasMany('BatchModel', 'Class');
}
public function studentadmissionresult(){
return $this->hasMany('StudentAdmissionModel', 'StudentCourse');
}
public $timestamps = true;
public static $rules = array(
'GradeName' => array('required', 'unique:class','regex:/^./'),
'GradeSection' => 'required',
'GradeCode' => array('required', 'unique:class')
);
public static $updaterules = array(
'GradeName' => array('required','regex:/^./'),
'GradeSection' => 'required',
'GradeCode' => array('required')
);
}
I following this tutorial:
https://github.com/Maatwebsite/Laravel-Excel
I have try following command :
composer require maatwebsite/excel": "~1.2.1
This actually has nothing to do with the package you are installing.
Explanation
When recreating the autoload files (composer dump-autoload) after the update Composer detected that you have two classes with the exact same name (but in different files).
Class SettingsController in SettingsController.php and SettingsControllerBackup.php
and class ClassModel in ClassModel.php and LoginModel.php
Composer will then choose to use one of the two (I'm not sure how it makes that decision, it's probably just the first one it finds) and will ignore the other occurrence. - Confirmed. Composer uses first match.
Solutions
Delete the files if you don't need them
Rename the class
A good and common practice is to name the class like the file. This is a simple way to avoid such collisions because two files in the same directory can't have the same name.

Categories