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.
Related
I have four tables:
Agroindustria
Pessoa
PessoaJuridica
Endereco
. Here are their Models:
Agroindustria
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Agroindustria extends Model
{
use SoftDeletes;
protected $table = "agroindustria";
protected $primaryKey = "CodAgroindustria";
public $incrementing = false;
protected $keyType = 'string';
public $fillable = ['CodAgroindustria, Porte'];
public $hidden = ['created_at', 'updated_at', 'deleted_at'];
public function pessoa () {
return $this->setConnection('diana')->hasOne(Pessoa::class, 'CodPessoa', 'CodAgroindustria');
}
public function pessoajuridica()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodPessoa', 'CodEndereco');
}
public function endereco()
{
return $this->setConnection('diana')->hasOne(PessoaJuridica::class, 'CodEndereco', 'CodEndereco');
}
public function estado(){
return $this->setConnection('diana')->hasOne(Estado::class, 'CodEstado', 'estado');
}
public function cidade(){
return $this->setConnection('diana')->hasOne(Cidade::class, 'CodCidade', 'cidade');
}
}
Pessoa:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Pessoa extends Model
{
// use SoftDeletes;
protected $table = "pessoa";
protected $primaryKey = "CodPessoa";
public $incrementing = false;
protected $keyType = 'string';
protected $connection = "diana";
public $hidden = ['created_at', 'updated_at', 'EXCLUIDO', 'LastSend'];
public $fillable = ['email', 'TelRes', 'TelCel'];
public function endereco()
{
return $this->hasOne('App\Endereco', 'CodEndereco', 'CodEndereco');
}
public function pessoafisica()
{
return $this->hasOne('App\PessoaFisica', 'CodPessoaFisica', 'CodPessoa');
}
public function pessoajuridica()
{
return $this->hasOne('App\PessoaJuridica', 'CodPessoaJuridica', 'CodPessoa');
}
}
The PessoaJuridica and Endereco Models are pretty much the same as the Pessoa Model.
When I soft delete my Agroindustria, the deleted_at column updates successfully, but I'm struggling with updating the EXCLUIDO column values from 0 to 1 in my other models.
Here's the delete function I created in my AgroindustriaController:
public function deletar (Request $request)
{
try {
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$Agroindustria->delete();
$Pessoa = Pessoa::findOrFail($request['CodPessoa']);
if ($Agroindustria->delete()) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
return response()->json([
'error' => false,
'data' => [
'message' => 'Dados deletados com sucesso',
]
]);
} catch (Exception $e) {
return response()->json([
'error' => true,
'message' => [$e->getMessage()]
]);
}
}
second line in try
$Agroindustria->delete();
write this line like this
$dlt = $Agroindustria->delete();
after that in your if condition put this variable $dlt like this
if ($dlt) {
DB::table('Pessoa')->where('CodPessoa', $Pessoa->CodPessoa)
->update(array('EXCLUIDO' => 1));
}
Solved it by doing:
$Agroindustria = Agroindustria::where('CodAgroindustria', $request['CodAgroindustria']);
$dlt = $Agroindustria->delete();
if ($dlt) {
Pessoa::where('CodPessoa', $request['CodPessoa'])
->update(array('EXCLUIDO' => 1));
PessoaJuridica::where('CodPessoaJuridica', $request['CodPessoaJuridica'])
->update(array('EXCLUIDO' => 1));
Endereco::where('CodEndereco', $request['CodEndereco'])
->update(array('EXCLUIDO' => 1));
}
Thank you all!
I am a newbie in Laravel. So I am trying to update my form but it kept returning fail because I used the findOrFail method on the Controller.
But when I tried to dump the Id, the Id does exists.
Only when I call it using the method, it returns null.
Route for update
Route::post('/alumni/updateProfile','AlumniController#update');
Update method
public function update(Request $request, User $user, Profile $profile)
{
$user->roles()->sync($request->roles);
$profile = Profile::findOrFail(Auth::user()->id);
$profile->name = $request->name;
$profile->matric_no = $request->matric_no;
$profile->contact_no = $request->contact_no;
$profile->address = $request->address;
$profile->batch_year = $request->batch_year;
$profile->graduation_year = $request->graduation_year;
$profile->date_of_birth = $request->date_of_birth;
$profile->area_of_interest = $request->area_of_interest;
$profile->start_date = $request->start_date;
$profile->company_name = $request->company_name;
$profile->job_title = $request->job_title;
$profile->social_network = $request->social_network;
$profile->save();
return view('/home', compact('profile'));
}
Profile model
class Profile extends Model
{
// protected $guarded = [];
protected $fillable = ['alumni_id'];
protected $table = 'profiles';
public $timestamps = false;
public function users()
{
return $this->belongsTo('App\User');
}
}
User model
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function profiles()
{
return $this->belongsTo('App\Profile');
}
public function hasAnyRoles($roles)
{
if($this->roles()->whereIn('name', $roles)->first()){
return true;
}
return false;
}
public function hasRole($role)
{
if($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
Glad if any of you noticed anything, thank you.
You can write findOrFail() in try catch blog and get the exception in catch blog to understand the error.
OR
you can write below code instead of findOrFail().
$profile = Profile::where('id', '=', Auth::user()->id);
if( $profile->count() ){
# Assignment of values to database columns fields and then save.
$profile->save();
} else {
# Print No Record Found.
}
i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?
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.
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);