laravel 4 send data from controller - laravel

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'));

Related

Set email verified to true if password reset is done

I'm trying to set email verified as true if the password reset is completed.
Currently, when a user (email not verified) requests a password reset, it does send an email and the user is able to change password.
As we can confirm that, email in fact belongs to that user, we should be able to set email verified to true. Currently, Laravel doesn't seem to know when an unverified email requests a password reset.
My reset function on ResetPasswordController.php is something like this(overridden to reset function of ResetsPasswords.php)
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request),
function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
How can I let laravel know that User now has a verified email?
Thank you
Laravel default "email_verified_at" is indeed a timestamp, so you can handle this in several ways:
in your reset method:
$response = $this->broker()->reset(
$this->credentials($request),
function ($user, $password) {
$this->resetPassword($user, $password);
$user->email_verified_at = Carbon\Carbon::now(); //add this line
$user->save(); //add this line
}
);
Now the user has a valid timestamp and you can "cast" it to a boolean like this in your User model:
On User.php model class:
//Some code
public bool isVerified(){
if(isset($this->email_verified_at)){
return true;
}
else{
return false;
}
}
Now you can use: $user->isVerified() to check if user has verified its email
Hope it helped!

Login by code seems to not work in laravel

Basically i'm trying to send by email a link that lets you login with a specific account and then redirects you to a page.
I can seccessfully generate link and send them via email using URL functionalities in laravel using this code:
Generating the link:
$url = "some/page/".$travel_id;
$link = URL::temporarySignedRoute(
'autologin', now()->addDay(), [
'user_id' => 3,
'url_redirect' => $url,
]
);
And sending the mail:
Mail::send('emails.travel', $data, function ($message) use ($data) {
$message->from('mail#mail.com', 'blablabla');
$message->to('reciever#mail.com', 'blablabla')->subject('test');
});
There is a route that catches the link sent by mail that is supposed to log you in with the user (in this case, the one with the id '3') and redirect you to some page but when it redirects, it prompts you to the login page, as if you are not logged.
Here is the route:
Route::get('/autologin', function (Request $request) {
$user = User::findOrFail($request->user_id);
if (! $request->hasValidSignature()) {
abort(403);
}
Auth::login($user);
return redirect($request->input('url_redirect'));
})->name('autologin');
When i try to do a Auth::check() after the Auth::login($user); it returns true, so is the user logged in?
I also tried to use Auth::loginUsingId($request->user_id); with no different results.
Any idea of what's happening?
So i found the problem,
I was logging in with a backpack user but i was using the default auth feature of laravel.
Turns out i need to use: backpack_auth()->login($user); instead of Auth::login($user); if i want to login using a backpack user.
Also use backpack_auth()->check() instead of Auth::check().

How to get Logged in user detail before redirecting to page after authentication in laravel

I am developing an web backend for swiggy type of application. In that back-end i want to display all restaurants added by that particular partner user in header and that drop-down will display on all pages, so i want to do that get all restaurants and store on some place so that header can access and display it on every page. so how to do this? I am try to execute below code
if (Auth::guard('partner')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
$user = $userId = Auth::id();
echo '<pre>';
print_r($user);
exit;
return redirect('partners/employees');
}
but it gives me error not able to get user id. i want to display user's restaurants list which is added by current user in system on every page header as dropdown list. so how can i achieve this.
you can access user id like this
$userId = Auth::guard('partner')->user()->id;
Auth::user()->id;
Also... this is weird. Typo?
$user = $userId = Auth::id();
$userId = Auth::user()->id;
$user = Auth::user();

Attach authenticated user to create

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.

codeigniter ion auth getting user id

I need to get the user id of the person logged in, so that i can run a query for that user. Im using ion auth, should i use a session or call it from the db, should i use a helper or not? anyway, heres what im trying to do:
example: how many work orders does logged in user have?
query would be: select * from work_orders WHERE status = "1" AND userid = "%THE LOGGED IN USER"
here is my controller, which doesnt have the "get user id" code:
public function index()
{
$this->load->view('templates/header');
$data['total_open_wo'] = $this->Home_model->total_open_wo();
$data['result'] = $this->Home_model->index();
$this->load->view('home', $data);
$this->load->view('templates/footer');
}
here is my model:
public function total_open_wo() {
$this->db->where('status', "1");
$this->db->where('tid', "NEED_THE_USER_ID");
$num = $this->db->count_all_results('work_orders');
return ($num);
}
Provided the user is logged in you can get the user ID by using the get_user_id() function in ion auth. On a related note in your model you need a $this->db->from() call to set the table to fetch the number of rows from.
public function total_open_wo() {
$userId = $this->ion_auth->get_user_id();
$this->db->where('status', '1');
$this->db->where('tid', $userId);
$this->db->from('work_orders');
$num = $this->db->count_all_results();
return $num;
}
Use the function $this->ion_auth->logged_in() to make sure that the user is logged in before calling the model function.
you can retrieve the logged in user details using user() method.
For example to get user id
echo $this->ion_auth->user()->row()->id;

Resources