I'm a beginner web developer
I'm trying to write a condition that will be fulfilled depending on what data the user will send
Condition if fulfilled by one hundred percent
But the condition else produces an error with the following text
Trying to get property 'unique_id' of non-object
If someone have info how to solv this problem I will be grateful
This is my code from controller
public function checkRestorePassword(Request $request)
{
$result['success'] = false;
$rules = [
'unique_id' => 'required',
];
$validation = Validator::make($request->all(), $rules);
if (empty($validation))
{
$result['error'] = "Enter the code that was sent to you by mail.";
return response()->json($result, 422);
}
$user = User::where('unique_id', $request->uniqueId)->first();
if ($user->unique_id === $request->uniqueId)
{
$result['success'] = 'Access to your personal account successfully restored. Please change your password.';
return response()->json($result, 200);
}
else
{
$result['success'] = false;
return response()->json($result, 422);
}
}
I think it's because $user is returning null.
so do this
if (!is_null($user) && $user->unique_id === $request->uniqueId)
Related
I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.
My code:
$obj = new Pengajuan();
// $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));
Above of the code add a validation like below:
$this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;
And then rest of your controller code.
try this:
public function store(Request $request)
{
$this->validate($request,[
'id_nasabah'=>'required|exists:your_table_name,id',
'tgl_pengajuan'=>'more_validations',
'besar_pinjaman'=>'more_validations',
]);
//if $this->validate() fails, it will return a response 422 code error
//else it will continue with the creation of your object
//is a good idea to use a try-catch in case of something goes wrong
try
{
$pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));
return response->json([
'pengajuan'=>$pengajuan,
'status'=>'Tersmpan',
],200);//return a http code 200 ok
}
catch(Exception $e)
{
//'message'=>'this will return what is the error and line'
return response()->json([
'message'=>$e->getMessage().'/'.$e->getLine(),
'status'=>'Gagal',
],422);
}
}
I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.
I have been trying to update the handicap score using a post request. But I seem to get an error saying : creating default object from empty value.
Code :
public function handicap(Request $request)
{
$user = Auth::user();
$rules = array(
'handicap' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails())
{
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
else {
if(Handicap::where('user_id', '=', $user->id)->exists())
{
$handicap = Handicap::find($user->id);
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}
else
{
$handicap = new Handicap;
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have added your handicap score successfully!'], 200);
}
}
}
If user does not exist in Handicap table then the else block code runs and creates a handicap score for the user else the if block needs to execute and update the score. I tried many alternatives but dont seem to get it working. Dont know what am I doing wrong.
I checked the $user, $handicap variables using return. those variables have the info that I need to add to the table. Its just that Its not updating.
Your problem probably comes from the line you have Handicap::find($user->id). Obviously it's null, because such model was not found, even though your if statement returns true.
In your if statement you have where('user_id' , '=', $user->id), but you are using Handicap::find($user->id) which is basically Handicap::where('id', '=', $user->id)->first().
Try changing it to:
$handicap = Handicap::where('users_id', '=', $user->id)->first();
You may give this a try:
public function handicap(Request $request)
{
$validator = Validator::make(Input::all(), [
'handicap' => 'required'
]);
// process the login
if ($validator->fails()) {
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
$handicap = Handicap::firstOrNew([
'user_id' => $request->user()->id;
]);
$handicap->user_id = $request->user()->id;
$handicap->handicap = $request->handicap;
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}
i want to add password update option for logged user therefore i used following code
controller auth\authController.php
public function updatePassword()
{
$user = Auth::user();
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::route('change-password', $user->id)->withErrors($validator);
} else {
if (!Hash::check(Input::get('old_password'), $user->password)) {
return Redirect::route('change-password', $user->id)->withErrors('Your old password does not match');
} else {
$user->password = Input::get('password');
$user->save();
return Redirect::route('change-password', $user->id)->with("message", "Password have been changed");
}
}
}
Routes
Route::post('change-password', 'Auth\AuthController#updatePassword');
Route::get('change-password', 'Auth\AuthController#updatePassword');
im getting following error
FatalErrorException in AuthController.php line 123:
Class 'App\Http\Controllers\Auth\Auth' not found
for this line "$user = Auth::user();"
Your question has hidden answer..I have similar problem like #faz..I have done the trick with his question's code actually
The correct way to achieve this -
protected function postChangePassword(ChangePasswordFormRequest $request){
$user = Auth::user();
$current_password = Input::get('current_password');
$password = bcrypt(Input::get('password'));
$user_count = DB::table('users')->where('id','=',$this->user_id)->count();
if (Hash::check($current_password, $user->password) && $user_count == 1) {
$user->password = $password;
try {
$user->save();
$flag = TRUE;
}
catch(\Exception $e){
$flag = FALSE;
}
if($flag){
return redirect('/u/0/change/password')->with('success',"Password changed successfully.");
}
else{
return redirect('/u/0/change/password')->with("danger","Unable to process request this time. Try again later");
}
}
else{
return redirect('/u/0/change/password')->with("warning","Your current password do not match our record");
}
}
Please note for Hash and Auth, we need to include class at the top and user_id I have get through constructor $this->user_id = Auth::user()->id;. I think I have helped people.
You didn't import Auth class.
add this at the top of the file. after the namespace.
use Illuminate\Support\Facades\Auth;
Its namespace issue, Try :
//if this method is not protected by a middleware for only authenticated users
//verify that user is currently logged in:
if(!$user = \Auth::user()) abort(503); //or return redirect()->route('login')
$rules = array(
'old_password' => 'required',
'password' => 'required|alphaNum|between:6,16|confirmed'
);
Or Add the namespace at the top of your AuthController
use Auth;
class AuthController{
....
}
As i can understand your issue you just use auth namespace of laravel, just write this line at top of your controller file
use Auth;
will solve your problem.
I have problem with Yii. I have following code in controller:
...
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
...
And Im getting this error:
Call to undefined method stdClass::save()
What's wrong?
oo i see you need to test if you have a user
just do :
if($user)
is your model extand a CactiveRecord ?
you should display the errors to know what's wrong
if(!$user->save()){
var_dump($user->getErrors());
}
this will be helpfull
Your error is to classic to knwo exactly what went wrong! here's a problem that could be the reason of your error:
When you find your user, if it doesn't find it the method will return false then the rest of the operations will fail. You should perform something like:
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
if($user !== null) {
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
}
if ($model->load(Yii::$app->request->post())) {
$model->startDate = $modifiedStartDate;
$model->timeFrom = $modifiedFromTime;
$model->timeTo = $modifiedToTime;
//echo '<pre>';
//print_r($model);exit;
$model->save();
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['timelog/index']);
} else {
return $this->render('create',
[
'model' => $model,
]);
}
//why the error occurs while using the $method->save(); function.