How to implement multi-user system login in laravel
laraveli adds one or more user tables, taking admin as an example.
Some file contents may need to be modified according to the actual situation
Recommended: laravel tutorial
Create an Admin model
php artisan make:model Admin -m
Write admins Table fields
Schema::create('admins', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
Edit admin model
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; /** * @property int $id * @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $updated_at */ class Admin extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'password','remember_token' ]; protected $hidden = [ 'password','remember_token' ]; }
Modify the auth.php configuration file
'guards' => [ ... 'admin' => [ 'driver' => 'session', 'provider' => 'admins' ] ], 'providers' => [ ... 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ] ],
Create the directory Admin/Auth under app/Http/Controllers
Create the file HomeController.php in the Admin directory (this file is used to test the jump page after successful login)
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class HomeController extends Controller { /** * HomeController constructor. */ public function __construct() { $this->middleware('auth:admin'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('admin.home'); } }
Use the command to generate a Request
php artisan make:request AdminLoginRequest
At this time in app/Http/Request This file is generated in the directory, and then edit this file
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class AdminLoginRequest extends FormRequest { /** * 确定用户是否有权发出此请求. * * @return bool */ public function authorize() { return true; } /** * 获取适用于请求的验证规则. * * @return array */ public function rules() { return [ 'name' => 'required', 'password' => ['required', 'min:6'] //密码必须,最小长度为6 ]; } }
Create the file LoginController.php
<?php namespace App\Http\Controllers\Admin\Auth; use App\Http\Controllers\Controller; use App\Http\Requests\AdminLoginRequest; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { public function showLoginForm() { return view('admin.auth.login'); } public function postLogin(AdminLoginRequest $loginRequest) { $data = $loginRequest->only('name', 'password'); $result = Auth::guard('admin')->attempt($data, true); if ($result) { return redirect(route('admin.home')); } else { return redirect()->back() ->with('name', $loginRequest->get('name')) ->withErrors(['name' => '用户名或密码错误']); } } public function postLogout() { Auth::guard('admin')->logout(); return redirect(route('admin.login.show')); } }
in the Admin/Auth directory to add routing. Open app/providers/RouteServiceProvider.php
Add a method after the method mapWebRoutes()
protected function mapAdminWebRoutes() { Route::middleware('web') ->prefix('admin') ->namespace($this->namespace) ->group(base_path('routes/admin.php')); }
Call the above added method in the map() method
public function map() { $this->mapApiRoutes(); $this->mapAdminWebRoutes();//调用新增的方法 $this->mapWebRoutes(); }
In Add a routing file admin.php to the routes directory
<?php Route::get('login','Admin\Auth\LoginController@showLoginForm') ->middleware('guest:admin') ->name('admin.login.show'); Route::get('/','Admin\HomeController@index') ->name('admin.home'); Route::post('login','Admin\Auth\LoginController@postLogin') ->middleware('guest:admin') ->name('admin.login.post'); Route::post('logout','Admin\Auth\LoginController@postLogout') ->middleware('auth:admin') ->name('admin.logout');
Copy home.blade.php to resources/views/admin
Copy layouts/app.blade.php to layouts/admin .blade.php, modify the corresponding place
<ul class="nav navbar-nav navbar-right"> <!-- Authentication Links --> @guest('admin') <li><a href="{{ route('admin.login.show') }}">admin Login</a></li> @else <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true"> {{ Auth::guard('admin')->user()->name }} <span class="caret"></span> </a> <ul class="dropdown-menu"> <li> <a href="{{ route('admin.logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ route('admin.logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> </ul> </li> @endguest </ul>
Copy login.blade.php to the admin/Auth directory
@extends('layouts.admin') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Admin Login</div> <div class="panel-body"> <form class="form-horizontal" method="POST" action="{{ route('admin.login.post') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}"> <label for="name" class="col-md-4 control-label">E-Mail Address</label> <div class="col-md-6"> <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus> @if ($errors->has('name')) <span class="help-block"> <strong>{{ $errors->first('name') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}"> <label for="password" class="col-md-4 control-label">Password</label> <div class="col-md-6"> <input id="password" type="password" class="form-control" name="password" required> @if ($errors->has('password')) <span class="help-block"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-8 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Login </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
Data filling
php artisan make:seed AdminsTableSeeder
Edit AdminsTableSeeder.php
public function run() { \App\Admin::insert([ 'name'=>'yzha5', 'password'=> bcrypt('123456') ]); } DatabaseSeeder.php $this->call(AdminsTableSeeder::class);
Upload the file to the server, log in to the server, and execute the fill command
php artisan migrate php artisan db:seed
At this time, opening http://xxx/admin directly will not jump to http://xxx/admin/ login, so some exceptions need to be handled. Open app/Exceptions/Handle.php
Rewrite the unauthenticated() method.
use Illuminate\Support\Facades\Route; protected function unauthenticated($request, AuthenticationException $exception) { return starts_with(Route::currentRouteName(), 'admin') ? redirect(route('admin.login.show')) : parent::unauthenticated($request, $exception); }
Improve the above code. When the admin logs in and accesses the URI /admin/login again, it will automatically jump to the URI /home. This is because of the guest middleware. By default, it jumps to /home, which is the file RedirectIfAuthenticated.php in the middleware directory.
The solution is:Create a single file named: RedirectIfAdminAuthenticated
php artisan make:middleware RedirectIfAdminAuthenticated
Edit this file:
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class RedirectIfAdminAuthenticated { /** * Handle an incoming request. * * @param $request * @param Closure $next * @param null $guard * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed */ public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { return redirect('/admin'); } return $next($request); } } 在Kernel.php中添加一行 protected $routeMiddleware = [ ... 'admin.guest' => \App\Http\Middleware\RedirectIfAdminAuthenticated::class, ... ]; 更改admin路由,将guest:admin改为admin.guest:admin Route::get('login','Admin\Auth\LoginController@showLoginForm') ->middleware('admin.guest:admin') ->name('admin.login.show'); Route::post('login','Admin\Auth\LoginController@postLogin') ->middleware('admin.guest:admin') ->name('admin.login.post');
The above is the detailed content of How to implement multi-user system login in laravel. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...
