Laravel set up the background login system steps _php instance

Source: Internet
Author: User
This paper describes the method of Laravel to build the background login system. Share to everyone for your reference, as follows:

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

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 background of the user table, I design the table is called badmin, each administrator has a user name (username), has a nickname (nickname), has a mailbox (email), has a password (password)

Play a flower here, use Laravel's migration to build the table (you can actually use this tool to build the table)

1. Install the most basic laravel frame

2 Create the Migration file:

./artisan Migrate:make Create-badmin-table

3 found app/database/migration/one more PHP file:

2014_10_19_090336_create-badmin-table.php

4 Add content to up and down;

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

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

<?phpreturn 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 ' and ' = ' Migrations ',);

6 Creating a data table:

./artisan Migrate--env=local

This time to the database to see, found a badmin table, the data structure is as follows:

CREATE TABLE ' badmin ' (' id ' int (ten) unsigned not NULL auto_increment, ' nickname ' varchar (+) COLLATE utf8_unicode_ci not NULL, ' username ' varchar (+) COLLATE utf8_unicode_ci not null, ' email ' varchar (+) COLLATE utf8_unicode_ci not null, ' P Assword ' varchar (COLLATE) utf8_unicode_ci not null, ' created_at ' timestamp not null DEFAULT ' 0000-00-00 00:00:00 ', ' upd Ated_at ' timestamp not NULL DEFAULT ' 0000-00-00 00:00:00 ', PRIMARY key (' id '), UNIQUE KEY ' badmin_nickname_unique ' (' Nickn Ame '), 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 here, this is the field created by default for each table Laravel, and can be automatically updated when using eloquent for additional deletions.

7 Create a model:

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

We have to implements UserInterface and Remindableinterface here.

8 associating the model with the Auth, modify the app/config/auth.php

<?phpreturn Array (//   Default user authentication driver   //can be database or eloquent   ' driver ' = ' eloquent ',   // Only when the driver for eloquent is useful   ' model ' = ' badmin ',);

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

9 OK, this time in fact the logical part has been set up, you can already use the Controller type

Auth::attempt (XXX) DO permission authentication

Auth::user () Get logged-in user (one badmin Class)
such as

10 Create a user login page below:

11 Set the route:

<?php//does not require login verification of the 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 ']);//interfaces that require login validation to operate Route::group (Array (' before ' = ' auth '), function () {  route::get (' user/logout ', [' as ' = ' logout ', ' uses ' = ') ' Usercontroller@getlogout ']);  Route::get (' User/dashboard ', [' as ' = ' dashboard ', ' uses ' = ' usercontroller@getdashboard ']);

12 Set Controller:

<?phpclass Usercontroller extends Basecontroller {//Login page Public Function GetLogin () {return View::make (' Us   Er.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 ();     }}//Logout public Function getlogout () {auth::logout ();   Return redirect::to (' User/login ');   } 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 Settings under 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 with address after authentication failed here

14 Setting views/user/login.blade.php

Here is a partial intercept:

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

Then the basic is done ...

Postscript

Laravel here auth mechanism is still very convenient, but migration use up always feel a little. Operation database is always separated by a layer, uncomfortable.

Here auth some simple user login mechanisms are already available, but if you want to do more complex user management permissions, it is estimated to use third-party components such as Sentry (Https://cartalyst.com/manual/sentry).

More interested in laravel related content readers can view this site topic: "Laravel Framework Introductory and Advanced tutorial", "PHP Excellent Development Framework Summary", "Smarty Template Primer Basic Tutorial", "PHP date and Time usage summary", "PHP object-oriented Programming introduction tutorial "," PHP String Usage Summary "," Introduction to Php+mysql Database Operations "and" PHP common database Operation Skills Summary "

It is hoped that this article is helpful to 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.