Laravel 4 - Eloquent relationship find by username - laravel

$picture = User::find(Session::get('user_id'))
->pictures()->where('approved', '=', '1')->first();
How can i modify this code according to username instead of Session::get('user_id')
Thanks.

if the user is logged in, try
$pictures = Auth::user()->pictures()->where('approved', '1')->first();
Update
regarding your comment:
try {
$pictures = User::where('name', $searchname)->firstOrFail()->pictures()->where('approved', '1')->first();
}
catch (Exception $e) {
// stuff to do, if no user is found
}

Related

Laravel - User validation id giving wrong response

I have this code in Laravel-8:
$userId = Auth::user()->id;
$companyId = Auth::user()->company_id;
$confirmUser = User::where('company_id', $companyId)->where('active', 1)
->where(function ($query) use($request) {
$query->where('email', $request->email);
})->whereNull('deleted_at')->first();
if(!$confirmUser){
return $this->error('The User already exists', 400);
}
If user already exists, I want to:
return $this->error('The User already exists', 400);
carry on with the operation.
dd($confirmUser); gives null
Yet the postman response is:
{"message":"The User already exists","error":true,"code":400}
How do I resolve this?
Thanks
$userId = Auth::user()->id;
$confirmUser = User::where('company_id', Auth::user()->company_id)->where('active', 1)
->where('email', $request->email)->whereNull('deleted_at')->first();
if($confirmUser){
return $this->error('The User already exists', 400);
}

Laravel change password issue

For Laravel change password I did like this but why it is not working.. Its not updating password. I have done login page, registration everything working. But this giving me lot of trouble. Below is my code.
$returnValue = DB::table('users')->where('users_id', $users_id)->where('password', bcrypt($request->opassword))->update(['password'=>bcrypt($request->npassword)]);
if($returnValue >= 1)
{
$success['message'] = "Password updated successfully..";
return $this->sendResponse($success);
}
else
{
$error = "Entered Old password is not valid..";
return $this->sendResponse($error);
}
At first import Hash at the top of the controller. like this below
use Illuminate\Support\Facades\Hash;
After this , validate old password match with your database like this below
$user = User::findOrFail($users_id);
if (Hash::check($request->password, $user->password)) {
$user->password = Hash::make($request->opassword);
$user->update(); // $user->save();
$success['message'] = "Password updated successfully..";
return $this->sendResponse($success);
} else {
$error = "Entered Old password is not valid..";
return $this->sendResponse($error);
}
Try this.
You have issues with your keys:
$returnValue = DB::table('users')
->where('id', $users_id)
->where('password', bcrypt($request->opassword))
->update(['password'=>bcrypt($request->npassword)]);

Why does Magento remove my frontend cookie after using customer/session?

I'm using Nginx and HHVM, I'm also using custom php files to interact with Magento.
When I run any PHP file the frontend cookie gets set properly, also the shoppingcart works fine.
However, whenever I use:
$session = Mage::getSingleton( 'customer/session' );
$session->login($login, $pass);
$session->setCustomerAsLoggedIn($customer);
The frontend cookie gets removed.
Question: why is that and what can I do to solve it?
Settings:
Complete example:
include_once('../app/Mage.php');
ob_start();
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$login = $v[0]; //username as email
$pass = $v[1]; //user password
try {
$customer = Mage::getModel("customer/customer");
$customer->website_id = Mage::app()->getWebsite()->getId();
$customer->loadByEmail($login);
$session = Mage::getSingleton( 'customer/session' );
$session->login($login, $pass);
$session->setCustomerAsLoggedIn($customer);
} catch(Exception $e) {
$returnJson['success'] = false;
$returnJson['error'] = $e;
}
We solved this issue by adding the HHVM ini setting:
hhvm.server.allow_duplicate_cookies = 0
More info: https://github.com/facebook/hhvm/issues/2758
Maybe not related, but why load the customer before even logging in, and you never check if the login function returns true or false. Also you manually set the customer as logged in, this is performed inside the login() function for you if the user/pass is correct. I would basically change the whole try..catch part to something like:
try {
$session = Mage::getSingleton( 'customer/session' );
if (!$session->login($login, $pass)) {
throw new Exception("Authentication failed");
}
$customer = $session->getCustomer();
// more stuff?
} catch(Exception $e) {
$returnJson['success'] = false;
$returnJson['error'] = $e;
}
Obviously not tested/proofread for lazy reasons. :)

Login Function use in custom module controller in magento

I am facing problem, I don't know how to use login functionality in my custom module controller without pasting whole code of login. I want to hit the login function through my controller and login function return the session/result.
Please any 1 can me out.
I have 1.4.2 version of magento.
What have you tried ? Have you took a look at the standard magento controller (Mage_Customer_AccountController::loginPostAction) ? it's not so much line of codes ..
$session = Mage::getSingleton('customer/session');
$session->login($username, $password);
and try...catch + message/error handling
Please look app/code/core/Mage/Customer/controllers/AccountController.php and public function loginPostAction(), you will get clear idea how magento handles exception
$session = Mage::getSingleton('customer/session');
try {
$session->login($username, $password);
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$value = Mage::helper('customer')->getEmailConfirmationUrl($login['username']);
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', $value);
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
$session->addError($message);
$session->setUsername($login['username']);
} catch (Exception $e) {
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}

Prevent subscriber saving in observer newsletter_subscriber_save_before Magento

I created an Observer to monitor the event subscriber_save_before. In this observer I handle a new field, the value of that is saved, but if some errors occurs I wanna the record not to be saved and to display only my error message. The throwException seems not to do the trick. The only method I think could work is to force the email field to null but wasn't able to achieve this.
In the subscriberController.php (Mage Core) I have this:
$email = (string) $this->getRequest()->getPost('email');
try {
if (!Zend_Validate::is($email, 'EmailAddress')) {
Mage::throwException($this->__('Please enter a valid email address.'));
}
This is my code (not working):
public function NewsletterSaveSubscriber($observer)
{
$subscriber = $observer->getEvent()->getSubscriber();
$name = Mage::app()->getRequest()->getParam('subscriber_name');
// server side validation
// no name specified
if (!Zend_Validate::is(trim($name), 'NotEmpty')) {
$session = Mage::getSingleton('core/session');
try {
Mage::throwException(Mage::helper('newsletter')->__('The name field cannot be empty!'));
} catch (Mage_Core_Exception $e) {
$session->addException($e, Mage::helper('newsletter')->__('There was a problem: %s', $e->getMessage()));
}
$observer->getRequest()->setPost('email', ''); // this code doesn't work
Mage::app()->getRequest()->setPost('email', ''); // this too
// Ohh nooo! The subscriber is stored :-(
return $this;
}
// save the name
$name = htmlspecialchars($name);
$subscriber->setSubscriberName($name);
return $this;
}
This will solve your probem:
//Error Message
$session = Mage::getSingleton('core/session');
$session->getMessages(true);
$session->addError(Mage::helper('cartware_automaticreview')->__('CouldĀ“t save.'));
// Ohh nooo! The subscriber is not stored :)
$controller = $observer->getControllerAction()->setFlag('',Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH,true);
$controller->getResponse()->setRedirect(Mage::app()->getRequest()->getServer('HTTP_REFERER'));
return;
Good luck!

Resources