Attach authenticated user to create - laravel

I'm trying to attach the currently logged in user to this request, so that I can save it in the database. Can someone point me in the right direction, please?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
So, I have come up with the following using array_merge, but there must be a better way, surely?
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = array('created_by' => Auth::user()->id, 'modified_by' => Auth::user()->id);
$merged_array = array_merge($input, $userDetails);
$leadStatus = $this->leadStatusRepository->create($merged_array);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}

So you can use Auth Facade to get information of currently logged user.
For Laravel 5 - 5.1
\Auth::user() \\It will give you nice json of current authenticated user
For Laravel 5.2 to latest
\Auth::guard('guard_name')->user() \\Result is same
In laravel 5.2, there is new feature called Multi-Authentication which can help you to use multiple tables for multiple authentication out of the box that is why the guard('guard_name') function is use to get authenticated user.
This is the best approach to handle these type of scenario instead of attaching or joining.
public function store(CreateLeadStatusRequest $request)
{
$input = $request->all();
$userDetails = \Auth::user(); //Or \Auth::guard('guard_name')->user()
$leadStatus = $this->leadStatusRepository->create($input);
Flash::success('Lead Status saved successfully.');
return redirect(route('lead-statuses.index'));
}
Hope this helps.

Related

How to check data selected using LOG:INFO Laravel

How I can check the selected elements that I pass from front end using Log::info? I tried using this but I dont know how to check the result, or maybe the code is wrong?
public function filterQuery(Request $request){
$name= $request->name;
$age= $request->age;
Log::info('Showing user profile for user: '.$name);
$query = user::query();
if(!empty($request->name)){
$query->where('name',$name);
}

Gathering data from multi page form, and adding additional data

So I'm data from a multi-page form, the data is stored like this.
I'm using this tutorial https://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
public function store(Request $request)
{
$user = $request->session()->get('user');
$user->save();
return redirect('/home');
}
That works fine. But how do I add additional data manually using the arrow function? For example, I need to set a status, the ip address, ect. Something like 'status' => 1
Assuming this is the only place you want to add these values to users, you could just add the values after you got it from the session:
public function store(Request $request)
{
$user = $request->session()->get('user');
$user->ip_address = '127.0.0.1';
$user->status = 1;
$user->save();
return redirect('/home');
}
you can add addition data like:
if your $user is laravel object then
$user->setAttribute('status', '1');
or $user if array then
$user['status']=1;

Laravel password reset with mongodb

I am migrating old project (done in zend framework) to laravel 5.5. Database is mongo db. I am using laravel-mongodb to connect laravel and mongo.
I already override laravel login functionality because table fields are not same as default laravel fields. Login is working fine.
At present when I try to reset password I am getting error message "We can't find a user with that e-mail address". How can I override reset password functionality?
In user table the field name are usrEmail and usrPassword. Working code of login is given below.
At present when I try to reset password I am getting error message We can't find a user with that e-mail address. How can I override reset password functionality?
In user table the field name are usrEmail and usrPassword. Working code of login is given below.
LoginController.php
protected function attemptLogin(Request $request)
{
$authUser = User::where('usrEmail', $request->email)
->whereIn('usrlId', [1, 2, 5, 6])
->first();
if($authUser) {
$password = md5(env('MD5_Key'). $request->password. $authUser->usrPasswordSalt);
$user = User::where('usrEmail', $request->email)
->where('usrPassword', $password)
->where('usrActive', '1')
->where('usrEmailConfirmed', '1')
->where('is_delete', 0)
->where('usrlId', 2)
->first();
if ($user) {
$updateLoginTime = User::find($user->_id);
$updateLoginTime->lastlogin = date('Y-m-d H:i:s');
$updateLoginTime->save();
$this->guard()->login($user, $request->has('remember'));
return true;
}
else {
return false;
}
}
return false;
}
Try placing this in your Auth/ResetsPasswordController.php
protected function credentials(Request $request)
{
$data = $request->only(
'password', 'password_confirmation', 'token'
);
$data['usrEmail'] = $request->get('email');
return $data;
}
By default the ->only( also includes the email field, but since it is different in your database we needed to override this function, which is by default defined in the ResetsPasswords trait.
This should ensure that any email field in the password reset flow (both on requesting the email and the form once you click the emailed link) will point to the right field in your database.

How to add expiry date condition to login function in laravel 5.2

In laravel 5.2, i want to add the condition so that only users where their expiry date is greater than today's date to login.
protected function getCredentials(Request $request)
{
return ['email' => $request->{$this->loginUsername()}, 'password' => $request->password];
}
The code does not accept adding:
'expires' => gte(Carbon::now())
Any help is appreciated
I don't think this is possible, even in Laravel 5.5. Taking a look at the retrieveByCredentials method in Illuminate\Auth\EloquentUserProvider which is used to get the user from the database, you can see that the query passes simple key/value combinations to the where method on the $query object, which equate to where key = value. This is from 5.5:
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
To achieve what you are after I would recommend doing this check after the user has logged in, in your controller for instance:
// Imagine this is the controller method where you're dealing with user logins
public function login(array $credentials)
{
if (! auth()->attempt($credentials)) {
// Handle what happens if the users credentials are incorrect.
}
$user = auth()->user();
if (Carbon::now()->gte($user->expires)) {
// User's account has expired, lets log them out.
auth()->logout();
// Return a redirect with a message or something...
}
// Handle a successful login.
}
I'm not sure if the auth() helper is available in 5.2, but you should be able to use the Auth facade to do the same thing, e.g. Auth::attempt(...).

laravel 4 send data from controller

I have validated and authenticated a user and upon authentication I redirect him to the 'dashboard view file'.
What I want know is how do I send that user's data along with the redirected command.
My function looks like this:
if($validator->passes()) {
/-- validate user --/
return Redirect::to('users/login')->with('message', 'Thanks for registering!');
I would appreciate it if someone helped me add the user's data.
Thanks
You can pass it:
$user = User::find(1);
return Redirect::to('users/login')
->withMessage('Thanks for registering!');
->withUser($user);
And get it in your controller
$user = Session::get('user');
Or you could just pass the id
return Redirect::to('users/login')
->with('message', 'Thanks for registering!');
->with('user_id', $user->id);
And search for it again
$user = User::find(Session::get('user_id'));

Resources