How laravel achieve multi-user login system

laraveli add one or more user tables to Example admin.

 

Parts of the file may need to be modified according to the actual situation

 

Creating a model Admin

php artisan make:model Admin -m

Write admins Field

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'

    ];

}

Auth.php modify configuration files

'guards' => [

    ...

    'admin' => [

        'driver' => 'session',

        'provider' => 'admins'

    ]

],

'providers' => [

    ...

    'admins' => [

        'driver' => 'eloquent',

        'model' => App\Admin::class,

    ]

],

Create a directory Admin / Auth in app / Http / Controllers

Create a file HomeController.php in the Admin directory (this file is used to test the jump page after login success)

<?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 point in the app / Http / Request catalog will generate the file, 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 a file LoginController.php in Admin / Auth directory

<?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'));

    }

}

Add routes. Open the app / providers / RouteServiceProvider.php

In the method mapWebRoutes () method adds a method later

protected function mapAdminWebRoutes()

    {

        Route::middleware('web')

            ->prefix('admin')

            ->namespace($this->namespace)

            ->group(base_path('routes/admin.php'));

    }

Call to increase above the map () method in the method

public function map()

    {

        $this->mapApiRoutes();

        $this->mapAdminWebRoutes();//调用新增的方法

        $this->mapWebRoutes();

    }

Add a route in the routes file admin.php 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');

Home.blade.php copy to resources / views / admin under

The layouts / app.blade.php copy was layouts / admin.blade.php, modify the appropriate 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 the login.blade.php to the next 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);

Files uploaded to the server, login server, execute the Fill command

php artisan migrate

php artisan db:seed

At this point, directly open http: // xxx / admin does not jump to the http: // xxx / admin / the Login , it is necessary to deal with some exceptions. Open the app / Exceptions / Handle.php

Rewrite 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);

    }

Perfect look

When the above code, when admin login, visit again / admin / login to this URI, will automatically jump to / home this URI, it is because this middleware guest jump to the default / home, which is RedirectIfAuthenticated in middleware directory. php file.

Solution is:

Creating a single piece, titled: 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');

These are the details of how laravel achieve multi-user login system

Learn more information, please visit:

Tencent T3-T4 standard boutique Daquan PHP Architect tutorial directory, as long as you read the guarantee pay rises to a higher level (continually updated)

Above hope to help everyone, many PHPer always encounter some problems and bottlenecks in the advanced time, write more business code no sense of direction, I do not know from where to start to ascend, which I compiled some information, including but not limited to: a distributed architecture, highly scalable, high-performance, high-concurrency, server performance tuning, TP6, laravel, YII2, Redis , Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, micro-services, Nginx, etc. more advanced knowledge required for advanced dry goods can be free for everyone to share , need to be added to my official group here .

Published 265 original articles · won praise 36 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43814458/article/details/105203628
Recommended