我有两张有用户的桌子,一张给公共用户,一张给工人。工人只能由其他工人创建,但是当我进入员工注册网址时,它会检测到我正在登录并将我重定向到家,我如何改变这种行为?
我已经尝试过在RedirectIfAuthenticated.php文件中注释掉handle函数的一部分,但是这会使用户在登录时能够访问登录链接。
我在RedirectIfAuthenticated.php中注释的函数:
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
// foreach ($guards as $guard) {
// if (Auth::guard($guard)->check()) {
// return redirect(RouteServiceProvider::HOME);
// }
// }
return $next($request);
}发布于 2021-01-22 10:41:06
在users表中,定义一个字段,允许您在用户的types之间进行不同的操作。
$table->string('type')->default('public');我定义了一个data type string字段,并给该字段一个默认值public。还有其他方法可以做到这一点,比如使data type成为一个integer和使用一个查找表,但是现在让我们保持简单,老实说,这并不重要。
然后,type就可以在您的user对象上访问;$user->type。
要为当前通过身份验证的type获取user,您可以使用auth()->user()->type或Auth::user()->type (不管是哪个,相同的结果)。
基于type的值,您将允许或拒绝对某些东西的访问。在您的示例中,您希望拒绝不属于type worker的用户创建type worker的用户。
不要重用register表单来创建新用户,创建一个新的支架(路由、控制器、视图等)。完成这项任务。下面是一个基本的例子,说明这是什么样子的。
routes/web.php
Route::group(['prefix' => 'admin', 'as' => 'admin.'], function () {
Route::resource('users', \App\Http\Controllers\UserController::class);
});resources/views/users/create.blade.php
@if ($errors->any())
@foreach ($errors->all() as $error)
{{ $error }}
@endforeach
@endif
<form action="{{ route('admin.users.store') }}" method="post">
@csrf
{{--
If the authenticated user is of type public
you can choose to either hide the option for choosing a user type
--}}
@if (auth()->user()->type != 'public')
<select name="type" id="type">
<option value="public">Public</option>
<option value="worker">Worker</option>
</select>
@endif
{{--
Or you can simply disable it
--}}
<select name="type" id="type" @if (auth()->user()->type == 'public') disabled @endif>
<option value="public">Public</option>
<option value="worker">Worker</option>
</select>
</form>app/Http/Controllers/UserController.php
class UserController extends Controller
{
public function __construct()
{
$this->middleware(['auth']);
}
public function create()
{
return view('users.create');
}
public function store(Request $request)
{
// perform some validation on the data coming in
// the value of the type field should be either public or worker
// other values should cause an error
$validator = Validator::make($request->all(), [
'type' => ['in:public,worker']
]);
// an additional check to prevent non workers creating worker users
// this could be extracted to a custom validation rule
if (auth()->user()->type != 'worker' && $request->type == 'worker') {
return redirect(route('admin.users.create')
->withErrors([
'unauthorised' =>
'You do not have authorisation to create users of type Worker'
)]
->withInput();
}
// Don't forget to add 'type' to the $fillable array on your user model
User::create($validator->validated());
return redirect(route('users.admin.create')->with(['success' => 'User created!')];
}
}以上是一个非常基本的实现,为您指出正确的方向。您可以将检查user是否为worker的功能提取到middleware中,创建gates和custom validation rules以使事物更可重用。
https://stackoverflow.com/questions/65835538
复制相似问题