Firstly, I login as user X, and I have a function like:
public function loginAs($userId)
{
Auth::loginUsingId($userId); // now use Y user
return response()->json(['logged' => Auth::check(), 'user' => Auth::user()]);
}
and when I try to print out Auth::check()
it returns TRUE which is fine so far I am logged now as user Y, the thing is that I do first login as an X user and then switch to another Y user but when I do call some other functoins it seems that the current user logged is still X, and I want to be Y the current user logged... This might have to do something with session or I dont know exactly how to do this thing, would be grateful if someone has any sample or have any idea how to achieve such things in Laravel 5.
Can you elaborate? I was able to switch users using the following:
use Auth;
class TempController extends Controller
{
public function index() {
$user = User::find(1);
Auth::login($user);
var_dump(Auth::user()->id); // returns 1
Auth::logout();
var_dump(Auth::user()); // returns null
$user = User::find(2);
Auth::login($user);
var_dump(Auth::user()->id); // returns 2
Auth::logout();
}
}
routes.php
Route::get('/temp', 'TempController@index');
If you run this, you can see the logged in user's id changes.
You should use impersonating There is a weblog post about that http://blog.mauriziobonani.com/easily-impersonate-any-user-in-a-laravel-application/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With