Home > PHP Framework > Laravel > How to implement multi-user system login in laravel

How to implement multi-user system login in laravel

藏色散人
Release: 2020-03-30 08:56:14
forward
3263 people have browsed it

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
Copy after login

Write admins Table fields

Schema::create('admins', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
Copy after login

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 = [
        &#39;name&#39;, &#39;password&#39;,&#39;remember_token&#39;
    ];
    protected $hidden = [
        &#39;password&#39;,&#39;remember_token&#39;
    ];
}
Copy after login

Modify the auth.php configuration file

&#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,
    ]
],
Copy after login

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

Use the command to generate a Request

php artisan make:request AdminLoginRequest
Copy after login

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

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(&#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;));
    }
}
Copy after login

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(&#39;web&#39;)
            ->prefix(&#39;admin&#39;)
            ->namespace($this->namespace)
            ->group(base_path(&#39;routes/admin.php&#39;));
    }
Copy after login

Call the above added method in the map() method

public function map()
    {
        $this->mapApiRoutes();
        $this->mapAdminWebRoutes();//调用新增的方法
        $this->mapWebRoutes();
    }
Copy after login

In Add a routing file admin.php to the routes directory

<?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;);
Copy after login

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(&#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>
Copy after login

Copy login.blade.php to the admin/Auth directory

@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
Copy after login

Data filling

php artisan make:seed AdminsTableSeeder
Copy after login

Edit 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);
Copy after login

Upload the file to the server, log in to the server, and execute the fill command

php artisan migrate
php artisan db:seed
Copy after login

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(), &#39;admin&#39;)
            ? redirect(route(&#39;admin.login.show&#39;))
            : parent::unauthenticated($request, $exception);
    }
Copy after login

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
Copy after login

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(&#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;);
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template