I am implementing this shipping cart for laravel (https://github.com/darryldecode/laravelshoppingcart/issues/250). When a user logs in I would like to continue their cart, for this to happen I would need to save the session id then merge that data on login.
The problem I am having is that when i flash the cart inside \app\Http\Controllers\Auth\LoginController.php, the session id changes. It seems that all files inside Auth changes when getId().
session()->flash('guest_cart', [
'session' => session()->getId(),
'data' => cart()->getContent()
]);
So if I flash the session else where, how do I merge it into the new user cart on login if I am not able to retrieve the the original getId()?
When I output dd(session()->all()); inside LoginController it shows an empty array. I would somehow need to capture session('guest_cart.data'); during login.
I tried adding this to LoginController.php
protected function authenticated(Request $request, $user){
if(Auth::check()){
$session_id = \Session::getId();
$cartObj = \Cart::session($session_id)->getContent();
if (\Auth::guest()) {
session()->flash('guest_cart', [
'session' => $session_id,
'data' => $cartObj
]);
}
dd(session()->all());
}
but again guest_cart returns an empty array because $session_id = \Session::getId(); has changed.
where would I create an event to retrieve during login? Can you point me towards a direction on how to accomplish this?
We can just override the authenticated() method in Auth\LoginController.php to save anything to the session. If you want to store only few values then just update it.
authenticated() method is called just after the user is logged in & it is defined empty in the trait AuthenticatesUsers used in LoginController.
use Illuminate\Http\Request;
protected function authenticated(Request $request, $user)
{
if(Auth::check){
//assuming that you have a cart relationship with user.
$cartData = Auth::user()->cart()->getContent();
$request->session()->put('cart_data', $cartData);
}
return redirect()->intended($this->redirectPath());
}
If you have a lot of things to do you can then create an event, then use listeners to listen to that event. We will call the event from authenticated method itself.
Related
i am creating session for some purpose but when user logout the purpose value becomes null but i want to use it after user logout.. the scenario is the session is created by admin and i want use this session for normal user but when admin logout its session also become null..
this is the logout code of laravel
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/');
}
Here's what you can do:
first get all the data you want to keep.
then delete all the session data.
then save the data in to the session.
then logout.
public function logout(Request $request)
{
// get the data first for example the user's name
$name = Auth::user()->name;
$this->guard()->logout();
$request->session()->invalidate();
// save the data into a new session
session(['name' => $name]);
return redirect('/');
}
then in your view you get the data like so:
#if(session('name'))
{{ session('name') }}
#endif
Here is my controller that holds the store function
public function store(Request $request)
{
$artisan = Artisan::create($request->all() + ['user_id' => Auth::user()]);
return $artisan;
}
Can figure out why Auth::user() is pushing a null value to the db instead of picking the current authenticated user id.
please help guys.
Auth::user() returns a instance of the User class (if the user is logged in).
You have to pick the id from it, like this:
$user_id = Auth::user()->id;
To get user data from Auth::user(), you have to follow this.
You have to use Auth class for login.
if (Auth::attempt(['email' => $email, 'password' => $password])) {}
You have to include all the routes under web middleware where you want to access authenticated user data.
Route::group(['middleware' => ['web']], function () {
Route::post('/dashboard', 'Controller#dashboard');
}
As the value comes from Session and web middleware has Session
activated.
I'm using the out of the box authentication in Laravel 5.2 (using artisan command make:auth). It works like a charm.
Thing is, I'd like to restrict login for only active users (deleted_at = NULL).
However when using soft deletes I cannot retrieve other models with a user_id foreign key (allthough the user has been deleted, I still have to access the users information).
What would be a good approach?
An alternative I came up with is to use an "active" boolean column instead of a "deleted_at" date column. This way, I could filter only user with "active"=TRUE and would have no problem whith foreign keys.
In this case, how could I restrict users to login only if "active" is set to TRUE?
Cheers!
The trait Laravel uses to authenticate in controllers has a handleUserWasAuthenticated() method. It checks for another method called authenticated() (which isn’t defined by default) and calls that before fully authenticating a user and letting them access your application. Therefore, if you define this method in your own AuthController, you can do any post-authentication checking such as if the user is active.
class AuthController
{
public function authenticated($request, $user)
{
if (! $user->is_active) {
// Throw exception, display error etc.
}
return redirect()->intended($this->redirectPath());
}
}
You can always pass any extra parameters to the Auth::attempt() method, like so:
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// Redirect to required route/url
}
From what I understand, you can do something similar for the deleted_at field as well.
In Auth\AuthController.php, add authenticated() function
use Auth;
class AuthController extends Controller
{
.
.
.
public function authenticated($request, $user) {
if (! $user->active) {
Auth::logout();
return redirect('login')->withErrors([
$this->loginUsername() => 'Your '.$this->loginUsername().' is not active. Please contact Administrators'
]);
}else {
return redirect()->intended($this->redirectPath());
}
}
I was developing an app to manage users. I need to access auth/register from logged in users. The default auth redirecting to home page.
It seems after registration, Auth automatically doing ::attempt.
How can I prevent it?
Assuming you use the RegistersUsers (or AuthenticatesAndRegistersUsers) trait in your controller you can override the postRegister method and simply not log the user in. You can see the original method here
Without logging it that would be:
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
return redirect($this->redirectPath());
}
My middleware is similar to Auth. It checks for a URL pattern (eg: /rest/*), and then looks for token in the request, retrieves its corresponding user from database. After that, I want to save that user in a variable so that I can get back to it later in any of the following controller. What's the best way?
Middleware:
public function handle($request, Closure $next)
{
$token = Input::get("token");
// get user data from database
$user = User::get_user_from_token($token);
// ?? -> How to pass $user to controller, so that ..
return $next($request);
}
In Controller:
public function profile_save() {
// I get the user back here without querying again
$user = ???
}
I would flash the data to the session. When you flash data it only stays there until the next request.
In your middleware add
Session::flash('user', $user);
Don't forget to add this at the top of your middle ware
use Session;
Then whenever you need to access your user use
Session::get('user');
Here is a link to the docs for reference
http://laravel.com/docs/5.0/session#flash-data
I'm using Laravel 5.1.
To pass parameters from the middleware to the controller you can add it to the Request object.
In the middleware:
public function handle($request, Closure $next)
{
$user = 'DB Call To Get User';
$age = 20;
$request->route()->setParameter('user', $user);
$request->route()->setParameter('age', $age);
return $next($request);
}
Then you can get the user in the controller from either the arguments:
public function TestAction(Request $request, User $user, $age)
{}
Or explicitly from the request object:
public function TestAction(Request $request)
{
$user = $request->route()->getParameter('user');
$age = $request->route()->getParameter('age');
}
Of course you can flash the data temporarily to the session or save it to the session itself and set an expiry time, but if you only need it to last for the lifetime of the request then i think this is a good way.
Hope this helps!