详解Laravel应用中模拟用户的方法(附代码步骤)

 2644

本篇文章给大家带来了关于Laravel的相关知识,其中主要介绍了Laravel Nova是什么?Laravel中应用中怎么模拟用户?感兴趣的朋友,下面一起来看一下,希望对大家有帮助。


详解Laravel应用中模拟用户的方法(附代码步骤)


Laravel Nova 的一个新特性是在控制面板中模拟用户。这很方便,原因很多。但对于我而言,当收到错误报告或问题,并希望看到用户所看到的内容时,模拟他们可以节省大量时间,因为您可以看到他们所看到的。

如果你也想在你的 Laravel 应用中实现该功能,Laravel Impersonate 包让这一点变得简单。

步骤 1. 安装软件包

  1. composer require lab404/laravel-impersonate

然后,打开 config/app.php 并将其添加都 providers 数组:

  1. 'providers' => [
  2.     // ...
  3.     Lab404\Impersonate\ImpersonateServiceProvider::class,
  4. ],

之后,打开 Models/User 并添加 trait:

  1. use Lab404\Impersonate\Models\Impersonate;
  2.  
  3. class User extends Authenticatable
  4. {
  5.     use Impersonate;


步骤 2. 模拟路由

Laravel Impersonate 包包含了一些模拟用户的方法,不过我发现将路由宏添加到 routes/web.php 文件中是最为简便的方法:

  1. Route::impersonate();

这给你一些命名路由:

  1. // Where $id is the ID of the user you want to impersonate
  2. route('impersonate', $id)
  3.  
  4. // Or in case of multi guards, you should also add `guardName` (defaults to `web`)
  5. route('impersonate', ['id' => $id, 'guardName' => 'admin'])
  6.  
  7. // Generate an URL to leave the current impersonation
  8. route('impersonate.leave')


步骤 3. Laravel Blade 模拟用例

Laravel Impersonate 设置就绪后,你可以使用 其中模板 helpers:

  1. @canImpersonate($guard = null)
  2.     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
  3. @endCanImpersonate

然后反转:

  1. @impersonating($guard = null)
  2.     <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
  3. @endImpersonating


步骤 4. 高级设置

另一个你可能会考虑的是,限制谁可以模拟其他用户,以及那些用户可以被模拟。在 Models/User 中,你可以添加以下方法:

  1. /**
  2.  * By default, all users can impersonate anyone
  3.  * this example limits it so only admins can
  4.  * impersonate other users
  5.  */
  6. public function canImpersonate(): bool
  7. {
  8.     return $this->is_admin();
  9. }
  10.  
  11. /**
  12.  * By default, all users can be impersonated,
  13.  * this limits it to only certain users.
  14.  */
  15. public function canBeImpersonated(): bool
  16. {
  17.     return ! $this->is_admin();
  18. }


本文网址:https://www.zztuku.com/detail-13821.html
站长图库 - 详解Laravel应用中模拟用户的方法(附代码步骤)
申明:本文转载于《learnku》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐