在Laravel 6.*或更高版本中,使用3/4用户名需要进行以下步骤:
php artisan make:controller Auth\CustomAuthController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\User;
class CustomAuthController extends Controller
{
use AuthenticatesUsers, RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
config/auth.php
配置文件中,更新providers
数组的users
部分,使用username
替代默认的email
:'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
'username' => 'username', // 修改为username
],
],
resources/views/auth/register.blade.php
和resources/views/auth/login.blade.php
中,将email
字段替换为username
:<div class="form-group">
<label for="username">Username</label>
<input id="username" type="text" class="form-control" name="username" value="{{ old('username') }}" required autofocus>
@error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
Auth\RegisterController
和Auth\LoginController
替换为我们自定义的控制器:use App\Http\Controllers\Auth\CustomAuthController;
Route::get('register', [CustomAuthController::class, 'showRegistrationForm'])->name('register');
Route::post('register', [CustomAuthController::class, 'register']);
Route::get('login', [CustomAuthController::class, 'showLoginForm'])->name('login');
Route::post('login', [CustomAuthController::class, 'login']);
Route::post('logout', [CustomAuthController::class, 'logout'])->name('logout');
以上步骤完成后,你的Laravel应用程序将使用用户名作为认证凭据,并允许用户使用3/4用户名进行注册和登录。
请注意,这只是一个简单的示例,你可能需要根据你的具体需求进行定制和改进。关于laravel的更多信息,你可以参考Laravel官方文档。
领取专属 10元无门槛券
手把手带您无忧上云