Laravel set up the background login system steps Detailed _php Example

Source: Internet
Author: User
Tags auth php class smarty template laravel migration

The example of this article describes the method of Laravel to build the backstage login system. Share to everyone for your reference, specific as follows:

Today want to use Laravel to build a background system, you need the simplest kind, there is a user login system, a trial, feel that laravel user login this piece to do is really happy. Of course, the premise is that you want the user management system is the simplest kind, that is, no user rights, can log on.

I don't use the default User table as an example, so it's easy to confuse some of the default settings with Laravel.

First confirm that the backstage user table, I design the table is called badmin, each administrator has the user name (username), has the nickname (nickname), has the mailbox (email), has the password (password)

Here to play a flower, use the laravel migration to create a table (actually you can not use this tool to create a table)

1 installation of the most basic laravel framework

2 Create Migration file:

./artisan Migrate:make Create-badmin-table

3 found app/database/migration/below a PHP file:

2014_10_19_090336_create-badmin-table.php

4 Add content to up and down;

<?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 ', m)->unique ();
        $table->string (' username ', m)->unique ();
        $table->string (' email ', m)->unique ();
        $table->string (' Password ',);
        $table->timestamps ();}
     );
   /**
   * Reverse the migrations.
   *
   * @return void
   *
   /Public Function down ()
   {
     Schema::d rop (' badmin ');
   }
}

5 Configuration of local database,app/config/local/database.php

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

6 Creating Data tables:

./artisan Migrate--env=local

This time to look at the database, we found that a badmin table, the data structure is as follows:

CREATE TABLE ' badmin ' (
 ' id ' int (a) unsigned not NULL auto_increment,
 ' nickname ' varchar (MB) COLLATE De_ci NOT NULL,
 ' username ' varchar (MB) COLLATE utf8_unicode_ci NOT NULL,
 ' email ' varchar (MB) COLLATE Unicode_ci NOT NULL,
 ' password ' varchar (+) COLLATE utf8_unicode_ci not NULL,
 ' created_at ' timestamp not null DEF Ault ' 0000-00-00 00:00:00 ',
 ' updated_at ' timestamp not NULL DEFAULT ' 0000-00-00 00:00:00 ',
 PRIMARY KEY (' id '), C9/>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;

To ask why there are more create_at and Update_at, this is laravel default for each table created by the field, and in the use of eloquent for the increase in the deletion of the two fields can automatically update

7 Create a model:

<?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 ',
   ];
}

There's got to be implements UserInterface and Remindableinterface.

8 The model and Auth Association, modify the App/config/auth.php

<?php return
Array (
   //Default user authentication driver
   //can be database or eloquent
   ' driver ' => ' eloquent '),
   // Only the drive for eloquent time only useful
   ' model ' => ' badmin ',
);

The driver can be eloquent or database, using eloquent to tell Auth component that the user authentication class is badmin this type of pipe. The model here has a namespace, which means that if your admin class is \yejianfeng\badmin, you should change it to ' \yejianfeng\badmin '

9 Well, this time in fact, the logical part has been built, you can already use in controller species

Auth::attempt (XXX) Do authority authentication

Auth::user () Get the logged-on user (a badmin Class)
Wait

10 to create a user login page below:

11 Setting the route:

<?php
//No login Authentication interface
route::get ('/', [' as ' => ' user.login ', ' uses ' => ' ' usercontroller@getlogin ']);
Route::get (' User/login ', [' as ' => ' login ', ' uses ' => ' usercontroller@getlogin ']);
Route::p ost (' User/login ', [' as ' => ' login ', ' uses ' => ' usercontroller@postlogin ']);
Interface
Route::group (Array (' Before ' => ' auth ') that requires logon authentication to operate, function ()
{
  route::get (' user/logout '), [' As ' => ' logout ', ' uses ' => ' usercontroller@getlogout ');
  Route::get (' User/dashboard ', [' as ' => ' dashboard ', ' uses ' => ' Usercontroller@getdashboard ']);


12 Set Controller:

<?php class Usercontroller extends Basecontroller {//Login page Public Function GetLogin () {return view::ma
   Ke (' user.login '); //Login operation Public Function Postlogin () {if (auth::attempt) (' Email ' =>input::get (' email '), ' password ' =
     >input::get (' password ')) {return redirect::to (' User/dashboard ')->with (' message ', ' successful login ');
     else {return redirect::to (' User/login ')->with (' message ', ' username password incorrect ')->withinput ();
     }//Log out Public function Getlogout () {auth::logout ();
   Return redirect::to (' User/login ');
   The Public Function Getdashboard () {return view::make (' User.dashboard ');
   ///Add new User Action Public function getcreate () {return view::make (' user.create ');
     ///Add new User Action 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 ' => ' registration failed '], 410);

 }
   }
}

13 Set down filter,app/filter.php

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

Go to/path for address after failed authentication here

14 Setting views/user/login.blade.php

Part of this interception:

As you can see, you can use Session::has and session::get directly here.

And then basically finished ...

Postscript

Laravel here the auth mechanism is still very convenient, but migration use up always feel a little suffocated. The operation of the database is always separated by a layer, uncomfortable.

There are a few simple user login mechanisms available here, but if you want to do more complex user admin rights, it's auth to use a third-party component such as Sentry (Https://cartalyst.com/manual/sentry).

More interested in laravel related content readers can view the site topics: "Laravel Framework Introduction and Advanced Course", "PHP Excellent Development Framework Summary", "Smarty Template Primer Tutorial", "PHP date and Time usage summary", "PHP object-oriented Program Design Introductory Course ", PHP string (String) Usage summary," PHP+MYSQL Database operation Introduction Tutorial "and" PHP common database Operation Skills Summary "

I hope this article will help you with the PHP program design based on Laravel framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.