本篇文章給大家?guī)砹岁P(guān)于Laravel的相關(guān)知識(shí),其中主要介紹了Laravel Nova是什么?Laravel中應(yīng)用中怎么模擬用戶?感興趣的朋友,下面一起來看一下,希望對(duì)大家有幫助。
Laravel Nova 的一個(gè)新特性是在控制面板中模擬用戶。這很方便,原因很多。但對(duì)于我而言,當(dāng)收到錯(cuò)誤報(bào)告或問題,并希望看到用戶所看到的內(nèi)容時(shí),模擬他們可以節(jié)省大量時(shí)間,因?yàn)槟梢钥吹剿麄兯吹降摹?/p>
如果你也想在你的 Laravel 應(yīng)用中實(shí)現(xiàn)該功能,Laravel Impersonate 包讓這一點(diǎn)變得簡(jiǎn)單。
步驟 1. 安裝軟件包
composer require lab404/laravel-impersonate
然后,打開 config/app.php 并將其添加都 providers 數(shù)組:
'providers' => [ // ... Lab404ImpersonateImpersonateServiceProvider::class, ],
之后,打開 Models/User 并添加 trait:
use Lab404ImpersonateModelsImpersonate; class User extends Authenticatable { use Impersonate;
步驟 2. 模擬路由
Laravel Impersonate 包包含了一些模擬用戶的方法,不過我發(fā)現(xiàn)將路由宏添加到 routes/web.php 文件中是最為簡(jiǎn)便的方法:
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 設(shè)置就緒后,你可以使用 其中模板 helpers:
@canImpersonate($guard = null) <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a> @endCanImpersonate
然后反轉(zhuǎn):
@impersonating($guard = null) <a href="{{ route('impersonate.leave') }}">Leave impersonation</a> @endImpersonating
步驟 4. 高級(jí)設(shè)置
另一個(gè)你可能會(huì)考慮的是,限制誰可以模擬其他用戶,以及那些用戶可以被模擬。在 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(); }
推薦學(xué)習(xí):《laravel視頻教程》