1. Enable Laravel authentication
Laravel’s Laravel/UI package provides a quick authentication method that supports all the routes and views you need to authenticate using a few simple commands:
composer require laravel/ui
php artisan ui vue --auth
Copy the code
This command should be used on the new application and will install the layout view, the registration and login views, and the routing of all authentication endpoints. A HomeController is also generated to handle post-login requests for the application dashboard.
2. Create the Admin model
php artisan make:model Admin -m
Copy the code
The migration is as follows:
Schema::create('admins'.function (Blueprint $table) {
$table->id();
$table->string("name".30)->default("")->comment("Name");
$table->string("email".50)->comment("Email")->nullable()->unique();
$table->string("phone".11)->comment("Telephone")->nullable()->unique();
$table->string("password".64)->default("")->comment("Password");
$table->string("profile")->default("")->comment("Introduction");
$table->rememberToken();
$table->timestamps();
});
Copy the code
3. Modify the Admin model to inherit Authenticatable
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use HasFactory.Notifiable;
/** * Define gateway *@var string
*/
protected $guard_name = 'admin';
protected $fillable = [
'name'.'email'.'phone'.'password'.'profile',];protected $hidden = [
'password'.'remember_token',]; }Copy the code
4. Customize Guards
Open the config/auth.php file to add custom Guards
'guards'= > ['web'= > ['driver'= >'session'.'provider'= >'users',].'admin'= > ['driver'= >'session'.'provider'= >'admins',].'api'= > ['driver'= >'token'.'provider'= >'users'.'hash'= >false,]],'providers'= > ['users'= > ['driver'= >'eloquent'.'model' => App\User::class,
],
'admins'= > ['driver'= >'eloquent'.'model' => App\Models\Admin::class,
],
],
'passwords'= > ['users'= > ['provider'= >'users'.'table'= >'password_resets'.'expire'= >60.'throttle'= >60,].'admins'= > ['provider'= >'admins'.'table'= >'password_resets'.'expire'= >60.'throttle'= >60,]],Copy the code
5. Create a custom authentication middleware
php artisan make:middleware AuthenticateBackend
Copy the code
Set authentication
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AuthenticateBackend
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request.Closure $next)
{
if (Auth::guard('admin')->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.'.401);
} else {
return redirect()->guest('admin/login'); }}return $next($request); }}Copy the code
Add custom authentication middleware to App\Http\ kernel.php
protected $routeMiddleware = [
//....
'admin' => \App\Http\Middleware\AuthenticateBackend::class,
];
Copy the code
6. Modify the authentication exception handler
Add the following method to app\Exceptions\ handler.php:
/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
response()->json(['message'= >$exception->getMessage()], 401);
}
if (in_array('admin'.$exception->guards())) {
return redirect()->guest('/admin/login');
}
return redirect()->guest(route('login'));
}
Copy the code
7. Create a base class for the background controller
php artisan make:controller Admin/AdminController
Copy the code
Setting authentication Guards
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin'); }}Copy the code
Add login controller
php artisan make:controller Admin/LoginController
Copy the code
The code is as follows:
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
class LoginController extends Controller
{
protected $redirectTo = '/admin';
public function __construct()
{
$this->middleware('guest:admin'['except'= >'logout']);
}
protected function guard()
{
return auth()->guard('admin');
}
/** * log in *@param Request $request
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
*/
public function login(Request $request)
{
if ($request->isMethod('post')) {
$validator = Validator::make($request->input(),
['email'= >'required'.'password'= >'required',],
['required'= >':attribute is mandatory '.'min'= >':attribute length does not meet requirements'],
['email'= >'account'.'password'= >'password']);if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
if ($this->guard()->attempt(['email'= >$request->email, 'password'= >$request->password])) {
return $request->ajax() || $request->wantsJson() ? new JsonResponse(['code'= >0].200) : redirect('/admin/login');
} else {
return $request->ajax() || $request->wantsJson() ? new JsonResponse(['code'= > -1].204) : back()->with('error'.'Incorrect account or password')->withInput(); }}return view('admin.login');
}
/** * Log out *@return mixed
*/
public function logout()
{
if($this->guard()->user()){
$this->guard()->logout();
}
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect('/admin/login'); }}Copy the code
8. Add routes
Route::get('/'.function () {
return view('welcome');
});
Auth::routes();
Route::get('/home'.'HomeController@index')->name('home');
Route::namespace('Admin')->group(function() {
Route::any('/admin/login'.'LoginController@login');
Route::any('/admin/logout'.'LoginController@logout')->name('admin.logout');
Route::get('/admin'.'DashboardController@index');
});
Copy the code
Split the route configuration file
Next, we will implement the configuration of the routes behind the foreground in a different routing configuration file, as follows:
routes\web.php
routes\admin.php
Copy the code
First, we need to create the admin.php configuration file in the Routes folder and pull out the configuration above
//routes\admin.php
Route::namespace('Admin')->group(function() {
Route::any('/admin/login'.'LoginController@login');
Route::any('/admin/logout'.'LoginController@logout')->name('admin.logout');
Route::get('/admin'.'DashboardController@index');
});
Copy the code
Loading route Configuration
app\Providers\RouteServiceProvider.php
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::middleware('admin')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
});
}
Copy the code
Adding a middleware group
app\Http\Kernel.php
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'admin' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api'= > ['throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Copy the code
The configuration is complete