成功登录后会话被销毁,或者防护功能出现一些无法保留会话的错误。当在仪表板视图中询问your_session_key时,它提供了null。
Route::group(['prefix' => 'admin'], function () {
Route::namespace('Admin')->group(function () {
Route::group(['middleware' => ['admin_middle','auth:admin']] , function () {
Route::get('accounts/', 'AccountsController@index')->name('admin.accounts');
});
});
});
中间件:App \ Http \ Middleware \ RedirectIfNotAdmin //在内核中注册为'admin_middle'=> \ App \ Http \ Middleware \ RedirectIfNotAdmin :: class,
class RedirectIfNotAdmin
{
public function handle($request, Closure $next, $guard = 'admin')
{
if (!auth()->guard($guard)->check()) {
$request->session()->flash('error', 'You must be an Admin to see this page');
return redirect(route('auth.admin.login'));
}
return $next($request);
}
}
Guard:config / auth.php //自定义Guard
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
AccountsController:Controllers \ AccountsController
AccountsController类扩展了Controller{
public function __construct(AdminRepositoryInterface $adminRepository) {
$this->adminRepo = $adminRepository;
}
private $adminRepo;
public function index(int $id)
{
$admin = $this->adminRepo->findAdminById($id);
$talentRepo = new AdminRepository($admin);
return view('admin.accounts');
}
}
AdminRepositoryInterface:App \ Shop \ Admins \ Repositories \ Interfaces \ AdminRepositoryInterface;
interface AdminRepositoryInterface extends BaseRepositoryInterface
{
public function findAdminById(int $id) : Admin;
}
AdminRepository:App \ Shop \ Admins \ Repositories \ AdminRepository
class AdminRepository extends BaseRepository implements AdminRepositoryInterface
{
public function findAdminById(int $id) : Admin
{
try {
return $this->findOneOrFail($id);
} catch (ModelNotFoundException $e) {
throw new AdminNotFoundException($e);
}
}
}
查看:admin \ accounts.blade
@if (Session::has('YOUR_SESSION_KEY'))
{{-- do something with session key --}}
@else
{{-- session key does not exist --}} //this has been printed is the ID variable is not passed
@endif
{{$admin->name}}
<br />{{$admin->email}}
是说$this->adminRepo
返回null
。
尝试在控制器的构造函数中初始化$this->adminRepo
。如果键入提示,请确保将其绑定到服务提供商中。