Rumah > rangka kerja php > Laravel > teks badan

laravel如何实现多用户体系登录

藏色散人
Lepaskan: 2020-03-30 08:56:14
ke hadapan
3218 orang telah melayarinya

laraveli添加一个或多个用户表,以admin为例。

部分文件内容可能需要根据实际情况修改

推荐:laravel教程

创建一个Admin模型

php artisan make:model Admin -m
Salin selepas log masuk

编写admins表字段

Schema::create('admins', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
Salin selepas log masuk

编辑admin模型

<?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 = [
        &#39;name&#39;, &#39;password&#39;,&#39;remember_token&#39;
    ];
    protected $hidden = [
        &#39;password&#39;,&#39;remember_token&#39;
    ];
}
Salin selepas log masuk

修改auth.php配置文件

&#39;guards&#39; => [
    ...
    &#39;admin&#39; => [
        &#39;driver&#39; => &#39;session&#39;,
        &#39;provider&#39; => &#39;admins&#39;
    ]
],
&#39;providers&#39; => [
    ...
    &#39;admins&#39; => [
        &#39;driver&#39; => &#39;eloquent&#39;,
        &#39;model&#39; => App\Admin::class,
    ]
],
Salin selepas log masuk

在app/Http/Controllers下创建目录Admin/Auth

在Admin目录下创建文件HomeController.php(这个文件用来测试登录成功后的跳转页面)

<?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(&#39;auth:admin&#39;);
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view(&#39;admin.home&#39;);
    }
}
Salin selepas log masuk

使用命令生成一个Request

php artisan make:request AdminLoginRequest
Salin selepas log masuk

此时在app/Http/Request目录下便生成了这个文件,然后编辑这个文件

<?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 [
            &#39;name&#39;     => &#39;required&#39;,
            &#39;password&#39; => [&#39;required&#39;, &#39;min:6&#39;] //密码必须,最小长度为6
        ];
    }
}
Salin selepas log masuk

在Admin/Auth目录下创建文件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(&#39;admin.auth.login&#39;);
    }
    public function postLogin(AdminLoginRequest $loginRequest)
    {
        $data = $loginRequest->only(&#39;name&#39;, &#39;password&#39;);
        $result = Auth::guard(&#39;admin&#39;)->attempt($data, true);
        if ($result) {
            return redirect(route(&#39;admin.home&#39;));
        } else {
            return redirect()->back()
                ->with(&#39;name&#39;, $loginRequest->get(&#39;name&#39;))
                ->withErrors([&#39;name&#39; => &#39;用户名或密码错误&#39;]);
        }
    }
    public function postLogout()
    {
        Auth::guard(&#39;admin&#39;)->logout();
        return redirect(route(&#39;admin.login.show&#39;));
    }
}
Salin selepas log masuk

添加路由。打开app/providers/RouteServiceProvider.php

在方法mapWebRoutes()方法后面增加一个方法

protected function mapAdminWebRoutes()
    {
        Route::middleware(&#39;web&#39;)
            ->prefix(&#39;admin&#39;)
            ->namespace($this->namespace)
            ->group(base_path(&#39;routes/admin.php&#39;));
    }
Salin selepas log masuk

在map()方法里调用上面增加的方法

public function map()
    {
        $this->mapApiRoutes();
        $this->mapAdminWebRoutes();//调用新增的方法
        $this->mapWebRoutes();
    }
Salin selepas log masuk

在routes目录下增加一个路由文件admin.php

<?php
Route::get(&#39;login&#39;,&#39;Admin\Auth\LoginController@showLoginForm&#39;)
    ->middleware(&#39;guest:admin&#39;)
    ->name(&#39;admin.login.show&#39;);
Route::get(&#39;/&#39;,&#39;Admin\HomeController@index&#39;)
    ->name(&#39;admin.home&#39;);
Route::post(&#39;login&#39;,&#39;Admin\Auth\LoginController@postLogin&#39;)
    ->middleware(&#39;guest:admin&#39;)
    ->name(&#39;admin.login.post&#39;);
Route::post(&#39;logout&#39;,&#39;Admin\Auth\LoginController@postLogout&#39;)
    ->middleware(&#39;auth:admin&#39;)
    ->name(&#39;admin.logout&#39;);
Salin selepas log masuk

把home.blade.php复制到resources/views/admin下

把layouts/app.blade.php复制为layouts/admin.blade.php,修改相应的地方

<ul class="nav navbar-nav navbar-right">
    <!-- Authentication Links -->
    @guest(&#39;admin&#39;)
        <li><a href="{{ route(&#39;admin.login.show&#39;) }}">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(&#39;admin&#39;)->user()->name }} <span class="caret"></span>
        </a>
        <ul class="dropdown-menu">
            <li>
                <a href="{{ route(&#39;admin.logout&#39;) }}"
                    onclick="event.preventDefault();
                    document.getElementById(&#39;logout-form&#39;).submit();">
                    Logout
                </a>
                <form id="logout-form" action="{{ route(&#39;admin.logout&#39;) }}" method="POST" style="display: none;">
                    {{ csrf_field() }}
                </form>
            </li>
        </ul>
    </li>
    @endguest
</ul>
Salin selepas log masuk

把login.blade.php复制到admin/Auth目录下

@extends(&#39;layouts.admin&#39;)
@section(&#39;content&#39;)
    <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(&#39;admin.login.post&#39;) }}">
                            {{ csrf_field() }}
                            <div class="form-group{{ $errors->has(&#39;name&#39;) ? &#39; has-error&#39; : &#39;&#39; }}">
                                <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(&#39;name&#39;) }}" required autofocus>
                                    @if ($errors->has(&#39;name&#39;))
                                        <span class="help-block">
                                        <strong>{{ $errors->first(&#39;name&#39;) }}</strong>
                                    </span>
                                    @endif
                                </div>
                            </div>
                            <div class="form-group{{ $errors->has(&#39;password&#39;) ? &#39; has-error&#39; : &#39;&#39; }}">
                                <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(&#39;password&#39;))
                                        <span class="help-block">
                                        <strong>{{ $errors->first(&#39;password&#39;) }}</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
Salin selepas log masuk

数据填充

php artisan make:seed AdminsTableSeeder
Salin selepas log masuk

编辑AdminsTableSeeder.php

public function run()
    {
        \App\Admin::insert([
            &#39;name&#39;=>&#39;yzha5&#39;,
            &#39;password&#39;=> bcrypt(&#39;123456&#39;)
        ]);
    }
DatabaseSeeder.php
$this->call(AdminsTableSeeder::class);
Salin selepas log masuk

文件上传至服务器,登入服务器,执行填充命令

php artisan migrate
php artisan db:seed
Salin selepas log masuk

此时,直接打开http://xxx/admin并不会跳转到http://xxx/admin/login,因此需要处理一些异常。打开app/Exceptions/Handle.php

重写unauthenticated()方法。

use Illuminate\Support\Facades\Route;
protected function unauthenticated($request, AuthenticationException $exception)
    {
        return starts_with(Route::currentRouteName(), &#39;admin&#39;)
            ? redirect(route(&#39;admin.login.show&#39;))
            : parent::unauthenticated($request, $exception);
    }
Salin selepas log masuk

完善一下

以上代码,当admin登录后,再次访问/admin/login这个URI时,会自动跳转到/home这个URI,这是因为guest这个中间件默认跳转到了/home,也就是middleware目录下的RedirectIfAuthenticated.php这个文件。

解决方法为:

创建一个中单件,名为:RedirectIfAdminAuthenticated

php artisan make:middleware RedirectIfAdminAuthenticated
Salin selepas log masuk

编辑这个文件:

<?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(&#39;/admin&#39;);
        }
        return $next($request);
    }
}
在Kernel.php中添加一行
protected $routeMiddleware = [
        ...
        &#39;admin.guest&#39; => \App\Http\Middleware\RedirectIfAdminAuthenticated::class,
        ...
    ];
更改admin路由,将guest:admin改为admin.guest:admin
Route::get(&#39;login&#39;,&#39;Admin\Auth\LoginController@showLoginForm&#39;)
    ->middleware(&#39;admin.guest:admin&#39;)
    ->name(&#39;admin.login.show&#39;);
Route::post(&#39;login&#39;,&#39;Admin\Auth\LoginController@postLogin&#39;)
    ->middleware(&#39;admin.guest:admin&#39;)
    ->name(&#39;admin.login.post&#39;);
Salin selepas log masuk

Atas ialah kandungan terperinci laravel如何实现多用户体系登录. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:segmentfault.com
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan