Skip to content

Instantly share code, notes, and snippets.

@dengsauve
Created May 15, 2019 00:33
Show Gist options
  • Save dengsauve/2e8ecbed4b9aafbfdc472fa3daa62c7e to your computer and use it in GitHub Desktop.
Save dengsauve/2e8ecbed4b9aafbfdc472fa3daa62c7e to your computer and use it in GitHub Desktop.
Laravel User Impersonation
<?php
namespace App\Nova\Actions;
use Illuminate\Bus\Queueable;
use Laravel\Nova\Actions\Action;
use Illuminate\Support\Collection;
use Laravel\Nova\Fields\ActionFields;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class ImpersonateUser extends Action
{
use InteractsWithQueue, Queueable, SerializesModels;
/**
* Perform the action on the given models.
*
* @param \Laravel\Nova\Fields\ActionFields $fields
* @param \Illuminate\Support\Collection $models
* @return mixed
*/
public function handle(ActionFields $fields, Collection $models)
{
return Action::redirect(
route('impersonate', $models[0])
);
}
/**
* Get the fields available on the action.
*
* @return array
*/
public function fields()
{
return [];
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
class ImpersonationController extends Controller
{
/**
* Impersonate the given user.
*
* @param User $user
* @return \Illuminate\Http\RedirectResponse
*/
public function __invoke(User $user)
{
auth()->login($user);
return redirect('/continuing-education/dashboard');
}
}
<?php
// fyi this is a nova resource
use App\Nova\Actions\ImpersonateUser;
//...
public function actions(Request $request) {
return [
new ImpersonateUser,
];
}
<?php
//...
// User Impersonation Route
Route::get('/admin/impersonate/{user}', 'ImpersonationController')->middleware('yourAuthMiddlewareHere')->name('impersonate');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment