Detailed explanation of steps to build backend login system in Laravel_php example

WBOY
Release: 2016-08-17 13:02:42
Original
905 people have browsed it

The example in this article describes how to build a backend login system in Laravel. Share it with everyone for your reference, the details are as follows:

Today I want to use laravel to build a backend system. I need the simplest one that allows users to log in to the system. After trying it out, I feel that laravel's user login is really happy. Of course, the premise is that the user management system you want is the simplest one, that is, you only need to be able to log in without user permissions.

I won’t use the default user table as an example here, as it would be easy to confuse it with some of Laravel’s default settings.

First confirm, the user table in the background, I designed the table to be called badin. Each administrator has a username, a nickname, an email, and a password

For fun here, use laravel's migration to create the table (actually you don't need to use this tool to create the table)

1 Install the most basic laravel framework

2 Create migration file:

./artisan migrate:make create-badmin-table

3 Found an additional php file under app/database/migration/:

2014_10_19_090336_create-badmin-table.php

4 Add content to up and down;

<&#63;php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBadminTable extends Migration {
   /**
   * Run the migrations.
   *
   * @return void
   */
   public function up()
   {
     Schema::create('badmin', function($table)
     {
       $table->increments('id');
        $table->string('nickname', 100)->unique();
        $table->string('username', 100)->unique();
        $table->string('email', 100)->unique();
        $table->string('password', 64);
        $table->timestamps();
     });
   }
   /**
   * Reverse the migrations.
   *
   * @return void
   */
   public function down()
   {
     Schema::drop('badmin');
   }
}

Copy after login

5 Configure the local database, app/config/local/database.php

<&#63;php
return array(
  'fetch' => PDO::FETCH_CLASS,
  'default' => 'mysql',
  'connections' => array(
    'mysql' => array(
      'driver'  => 'mysql',
      'host'   => 'localhost',
      'database' => 'test',
      'username' => 'yejianfeng',
      'password' => '123456',
      'charset'  => 'utf8',
      'collation' => 'utf8_unicode_ci',
      'prefix'  => '',
    ),
  ),
  'migrations' => 'migrations',
);

Copy after login

6 Create data table:

./artisan migrate --env=local

When I went to the database to look at this time, I found that there was an additional badmin table with the following data structure:

CREATE TABLE `badmin` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `nickname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `username` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `password` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
 `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
 PRIMARY KEY (`id`),
 UNIQUE KEY `badmin_nickname_unique` (`nickname`),
 UNIQUE KEY `badmin_username_unique` (`username`),
 UNIQUE KEY `badmin_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Copy after login

I want to ask why create_at and update_at are added here. These are the fields created by laravel for each table by default, and these two fields can be automatically updated when using Eloquent to perform additions, deletions, modifications and queries

7 Create a Model:

<&#63;php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Badmin extends Eloquent implements UserInterface, RemindableInterface {
   use UserTrait, RemindableTrait;
   protected $table = 'badmin';
   protected $hidden = array('password');
   public static $rules = [
     'nickname' => 'required|alpha_num|min:2',
     'username' => 'required',
     'email'=>'required|email|unique:badmin',
     'password'=>'required|alpha_num|between:6,12|confirmed',
   ];
}

Copy after login

You must implement UserInterface and RemindableInterface here

8 Associate the model with Auth and modify app/config/auth.php

<&#63;php
return array(
   // 默认的用户验证驱动
   // 可以是database或者eloquent
   'driver' => 'eloquent',
   // 只有驱动为eloquent的时候才有用
   'model' => 'Badmin',
);

Copy after login

The driver here can be eloquent or database. Using eloquent tells the Auth component that the user authentication class is managed by the Badmin class. The model here has a namespace, that is to say, if your admin class is YejianfengBadmin, it should be changed to 'YejianfengBadmin'

9 Okay, at this time, the logic part has actually been built, and you can already use it in the controller

Auth::attempt(XXX) for authority authentication

Auth::user() gets the logged in user (a Badmin class)
wait.

10 Next, create a user login page:

11 Set routing:

<&#63;php
// 不需要登录验证的接口
Route::get('/', ['as' => 'user.login','uses'=>'UserController@getLogin']);
Route::get('user/login', ['as' => 'login', 'uses' => 'UserController@getLogin']);
Route::post('user/login', ['as' => 'login', 'uses' => 'UserController@postLogin']);
// 需要登录验证才能操作的接口
Route::group(array('before' => 'auth'), function()
{
  Route::get('user/logout', ['as' => 'logout', 'uses' => 'UserController@getLogout']);
  Route::get('user/dashboard', ['as' => 'dashboard', 'uses' => 'UserController@getDashboard']);
});

Copy after login

12 Set controller:

<&#63;php
class UserController extends BaseController {
   // 登录页面
   public function getLogin()
   {
     return View::make('user.login');
   }
   // 登录操作
   public function postLogin()
   {
     if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))) {
       return Redirect::to('user/dashboard')
       ->with('message', '成功登录');
     } else {
       return Redirect::to('user/login')
          ->with('message', '用户名密码不正确')
          ->withInput();
     }
   }
   // 登出
   public function getLogout()
   {
     Auth::logout();
     return Redirect::to('user/login');
   }
   public function getDashboard()
   {
     return View::make('user.dashboard');
   }
   // 添加新用户操作
   public function getCreate()
   {
     return View::make('user.create');
   }
   // 添加新用户操作
   public function postCreate()
   {
     $validator = Validator::make(Input::all(), User::$rules);
     if ($validator->passes()){
        $bAdmin = new Badmin();
        $bAdmin->nickname = Input::get('nickname');
        $bAdmin->username = Input::get('username');
        $bAdmin->email = Input::get('email');
        $user->password = Hash::make(Input::get('password'));
        $user->save();
        Response::json(null);
     } else {
        Response::json(['message' => '注册失败'], 410);
     }
   }
}

Copy after login

13 Set filter, app/filter.php

Route::filter('auth', function()
{
   if (Auth::guest())
   {
     if (Request::ajax())
     {
        return Response::make('Unauthorized', 401);
     }
     else
     {
        return Redirect::guest('/');
     }
   }
});

Copy after login

Change the address after authentication failure here to the / path

14 Set views/user/login.blade.php

Here is a part:

As you can see, Session::has and Session::get can be used directly here

Then it’s basically done...

Postscript

The auth mechanism in laravel is still very convenient, but using migration always feels a bit frustrating. There is always a layer of separation when operating the database, which is annoying.

The auth here is enough for some simple user login mechanisms, but if you want to do more complex user management permissions, you may need to use third-party components like Sentry (https://cartalyst.com/manual/sentry).

Readers who are interested in more Laravel-related content can check out the special topics of this site: "Introduction and Advanced Tutorial on Laravel Framework", "Summary of Excellent PHP Development Framework", "Basic Tutorial on Smarty Templates", "Summary of PHP Date and Time Usage" ", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope what is described in this article will be helpful to everyone’s PHP program design based on the Laravel framework.

Related labels:
source:php.cn
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