我是laravel的初学者。我正在使用laravel auth,我将用户角色的一个字段添加到我迁移的用户表中。然后,我用两个角色注册到应用程序,例如admin和user。但是当我登录然后在用户详细信息的帮助下,它将自动检查用户的角色并分别加载管理视图或用户视图。因此,中间件将在视图和控制器之间调用。事情是如何发生的。在此先感谢。
我的代码:
RegisterController.php
protected function validator(array $data)
{
return Validator::make($data, [
.....
'role' => 'required|min:4|',
]);
}
protected function create(array $data)
{
return User::create([
....
'role' => $data['role'],
]);
}
AdminController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('home');
}
}
AdminMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
public function handle($request, Closure $next)
{
if ($request->user()->role != 'admin')
{
return redirect('home');
}
if ($request->user()->role != 'user')
{
return redirect('user');
}
return $next($request);
}
}
Route.php
Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function()
{
Route::get('/home', function()
{
return view('home');
});
});
kernel.php
protected $routeMiddleware = [
....
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];