Notes on the operation of laravel 7 online education project -- background basic function development

Basic functions: background login, exit, background home page display
1. Create administrator data table
Data dictionary: often used in later development projects. The data dictionary is to show the information of the fields in the data table in a tabular form.

Table name: manager

 

1,Create migration file
php artisan make:migration create_manager_table
2,Code migration files,File location: database/migrations/
public function up()
    {
        Schema::create('manager', function (Blueprint $table) {
            $table->increments('id');  //Primary key
            $table->string('username',20)->notNULL(); //User name
            $table->string('password')->notNULL(); //Password
            $table->enum('gender',[1,2,3])->notNULL()->default('1'); //Gender 1 male 2 female 3 confidential
            $table->string('mobile',11); //Mobile phone
            $table->string('email',50); //mailbox
            $table->tinyInteger('role_id'); //role
            $table->timestamps(); //time
            $table->rememberToken(); //Remember to log in
            $table->enum('status',[1,2])->notNULL()->default('2'); //Account status

        });
    }
    public function down()
    {
//Delete table method Schema::dropIfExists('manager'); }

3. Perform migration file

php artisan migrate:install / / use the migration log for the first time

php artisan migrate

4. Quickly fill in data

Plugin faker

Create the stuffer file PHP artican make: seeder managertableseeder

Refer to: https://packagist.org/packages/fzaninotto/faker

Tip: in laravel, the system provides a function of user password encryption: bcrypt, syntax: bcrypt (password civilization)

database\seeds\ManagerTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class ManagerTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create("zh_CN");
        for($i=0;$i<100;$i++) {
            $data[] = [
                'username' => $faker->username,
                'password' => bcrypt("123456"),
                'gender' => mt_rand(1, 3),
                'mobile' => $faker->phoneNumber,
                'email' => $faker -> email,
                'role_id' => mt_rand(1, 6),
                'created_at' => date('y-m-d H:i:s', time()),
                'status' => mt_rand(1, 2)
            ];
        }
         DB::table('manager')->insert($data);
    }
}

Execute the stuffer file PHP artican DB: seed -- class = managertableseed

5. Display of background login page

Determine route / admin/public/login

Add routes to routes/web.php

Route::group(['prefix'=>'admin'],function () {
    Route::get('public/login',  'Admin\PublicController@login');
});

6. Create controller file

php artisan make:controller Admin\PublicController

7. Create the required login method and add it in app\Http\Controllers\Admin\PublicController.php

public function login(){
       return view('admin.public.login');


    }

8. Create the required view file and use the h-ui admin template to demonstrate http://www.h-ui.net/H-ui.admin.shtml

Copy the login.html file to / resources/views/admin/public /. If there is no admin/public folder, create it by yourself

Change the name of login.html to login.blade.php, and replace the js css file address used in the page with the actual file address in the project

9. Login page verification code add

Download address of verification code: https://packagist.org/packages/mews/captcha installation command: composer require mews/captcha

10. Configure the providers and aliases array in the config/app.php file

In providers, add Mews\Captcha\CaptchaServiceProvider::class,

In aliases, add 'captcha' = > mews \ captcha \ facades \ captcha ',

11. Modify the template verification code image url to {{Captcha::src('edu ')}}}

edu configures the address vendor\mews\captcha\config\config.php for itself

'edu' => [
        'length' => 4,
        'width' => 120,
        'height' => 36,
        'quality' => 90,
        'math' => false,
    ],

12. Automatic verification of administrator login route of submitted route address: admin/public/check post

Change the url to receive the user name and password in the template file to / admin/public/check

13. Add hidden field for csrf validation add location: from any location in the form, such as {{csrf _field()}} < / from >

14 remember that the login function adds a default value such as value=1 to the keep me logged in check box

<input type="checkbox" name="online" id="online" value="1">
            Keep me logged in < / label >

15 write check method

Syntax: $this - > validate ($request, [rule array]);

public function check(Request $request){
        $this->validate($request,[
            'username' =>'required|min:2|max:20',  //Min 2 max 20 bits
            'password' =>'required|min:6',  //The smallest 6 bits
            'captcha'  =>'required|size:4|captcha', //Length of verification code

        ]);

16 display the error message when the automatic verification fails on the login template page

<SCRIPT type="text/javascript">
    @if (count($errors) > 0)

        var allError="";
        @foreach ($errors->all() as $error)
            allError +="{{$error}}<br>";

        @endforeach
layer.alert(allError,{title:'Error prompt'});
    layer.msg(allError, {
        time: 20000, //Turn off automatically after 20s
        btn: ['Determine']
    });

    @endif

</SCRIPT>  //Remember to introduce layer using the layerjs plug-in

17. Administrator authentication

Syntax: auth:: Guard (specify guard instance) - > attempt (Association array of user information to be verified, [bool value]);

Due to the need for auth facade, it is introduced in PublicController.php

use Auth;

18. Add guard instance in / config/auth.php

Add to the guards array following the original official instance

 'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],

Add to providers array

'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin\Manager::class,
        ],

/ / 'model' = > app \ admin \ Manager:: class add the model for instance creation later

19. Create a model to use (needed for guard)

php artisan make:model Admin/Manager

20. Define the basic properties of the model: add in the app\Admin\Manager.php file

protected $table ='manager '; / / define the mysql table that needs to be associated with the current model

Remember to add in class manager extensions

21. Continue to authenticate the PublicController.php file

Add $data = $request - > only (['username ','password']);
        $data['status'] = '2';
        $result=Auth::guard('admin')->attempt($data,$request->get('online'));

dd($result); if the result is false, the verification is not successful

 

22. Error will be reported when the verification is correct

Modify app\Admin\Manager.php

Add use Illuminate\Auth\Authenticatable;

class Manager extends Model implements \Illuminate\Contracts\Auth\Authenticatable

Add use Authenticatable;

Full code:

<?php

namespace App\Admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;

class Manager extends Model implements \Illuminate\Contracts\Auth\Authenticatable
{
    //
    protected  $table = 'manager';
    use Authenticatable;
}

23. Judge the jump direction according to the error information:

Syntax: return direct - > with errors ([array of error information]);

if($result){
            return redirect("/admin/index/index");
        }
        else{
            return redirect("/admin/public/login")->withErrors(['loginerror'=>'Wrong user name and password']);
        }

Full code:

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;

class PublicController extends Controller
{
    //Display of login page
    public function login(){
       return view('admin.public.login');


    }
    public function check(Request $request){
        $this->validate($request,[
            'username' =>'required|min:2|max:20',
            'password' =>'required|min:6',
            'captcha'  =>'required|size:4|captcha',

        ]);

        //Proceed with identity verification
        $data= $request -> only(['username','password']);
        $data['status'] = '2';
        $result=Auth::guard('admin')->attempt($data,$request->get('online'));
        if($result){
            return redirect("/admin/index/index");
        }
        else{
            return redirect("/admin/public/login")->withErrors(['loginerror'=>'Wrong user name and password']);
        }
    }
    //Logout is the added logout method
    public function logout(){
        Auth::guard('admin')->logout();
        return redirect("/admin/public/login");


    }
}
//Remember to add the logout rule route:: get ('public / logout ',' admin \ publiccontroller @ logout ') in web.php;

Display of backstage home page

Define the routing agreement of the background home page: / admin / index / index / admin / index / welcome

24. Add routing in web.php
Route::get('index/welcome','Admin\IndexController@welcome');
Route::get('manager/index','Admin\Managercontroller@index');

25. Create the required controller file

 php artisan make:controller Admin/IndexController

26. Write index method and welcome method to show their views

public function index(){
        return view('admin.index.index');


    }
    public  function welcome(){
        return view('admin.index.welcome');

    }

27. Create the two view files needed (index.blade.php and welcome.blade.php)

Copy the index.html welcome.html file in the h-ui admin template folder to resources\views\admin\index \ and change its name to index.blade.php welcome.blade.php

If no folder is created manually

Remember to modify the js css path required by the template

28. Get the logged in user name

{{Auth::guard('admin')->user()->username}}

29. Routing protection syntax: - > middleware (middleware name)

The routes to be protected in web.php are as follows

 Route::get('index/welcome','Admin\IndexController@welcome')->middleware('auth:admin');
 Route::get('manager/index','Admin\Managercontroller@index')->middleware('auth:admin');

It can also be grouped as

Route::group(['prefix'=>'admin'],function () {
    Route::get('public/login',  'Admin\PublicController@login')->name('login');
    Route::post('public/check', 'Admin\PublicController@check');
    Route::get('public/logout', 'Admin\PublicController@logout');
});
Route::group(['prefix'=>'admin','middleware'=>'auth:admin'],function () {
    Route::get('index/index','Admin\IndexController@index');
    Route::get('index/welcome','Admin\IndexController@welcome');
    Route::get('manager/index','Admin\Managercontroller@index');
});

Note: a. It is necessary to judge whether all login pages are protected by middleware;

b. When skipping, the system uses the login route alias by default. If not, it will report the error "route cannot be found". Therefore, you need to add the login route alias;

Tags: PHP Database Mobile Laravel

Posted on Tue, 24 Mar 2020 07:07:32 -0400 by ytse