如何在Laravel应用中模拟用户
Laravel Nova 的一个新特性是在控制面板中模拟用户。这很方便,原因很多。但对于我而言,当收到错误报告或问题,并希望看到用户所看到的内容时,模拟他们可以节省大量时间,因为您可以看到他们所看到的。
如果你也想在你的 Laravel 应用中实现该功能,Laravel Impersonate 包让这一点变得简单。
步骤 1. 安装软件包
composer require lab404/laravel-impersonate
然后,打开 config/app.php 并将其添加都 providers 数组:
'providers' => [
// ...
Lab404\Impersonate\ImpersonateServiceProvider::class,
],
之后,打开 Models/User 并添加 trait:
use Lab404\Impersonate\Models\Impersonate;
class User extends Authenticatable
{
use Impersonate;
步骤 2. 模拟路由
Laravel Impersonate 包包含了一些模拟用户的方法,不过我发现将路由宏添加到 routes/web.php 文件中是最为简便的方法:
Route::impersonate();
这给你一些命名路由:
// Where $id is the ID of the user you want to impersonate
route('impersonate', $id)
// Or in case of multi guards, you should also add `guardName` (defaults to `web`)
route('impersonate', ['id' => $id, 'guardName' => 'admin'])
// Generate an URL to leave the current impersonation
route('impersonate.leave')
步骤 3. Laravel Blade 模拟用例
Laravel Impersonate 设置就绪后,你可以使用 其中模板 helpers:
@canImpersonate($guard = null)
<a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
@endCanImpersonate
然后反转:
@impersonating($guard = null)
<a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
@endImpersonating
步骤 4. 高级设置
另一个你可能会考虑的是,限制谁可以模拟其他用户,以及那些用户可以被模拟。在 Models/User 中,你可以添加以下方法:
/**
* By default, all users can impersonate anyone
* this example limits it so only admins can
* impersonate other users
*/
public function canImpersonate(): bool
{
return $this->is_admin();
}
/**
* By default, all users can be impersonated,
* this limits it to only certain users.
*/
public function canBeImpersonated(): bool
{
return ! $this->is_admin();
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
以前刚入行时,为了方便给客户演示各个用户的权限问题,,,自己就弄了个小功能,只在开发测试环境开放,右下角可以选择用户直接登录,,,
就怕想不到,实现很简单