Laravel Implementing user Registration and login _php instances

Source: Internet
Author: User
Tags csrf attack
Laravel as the most elegant PHP framework, a lot of PHP-learning partners to create a laravel mouth-watering. Come to realize your wish today, let us start from scratch, using laravel to achieve the most common registration and login features of Web Applications! All course sources are on GitHub: Laravel-start. Race Start!

Let's start by defining what we need for this course:

Laravel 4.2
Bootstrap 3.3
Laravel is a central part of our concern, and bootstrap is used to quickly set up some front-end CSS styles.

1. Installing Laravel

After a brief explanation we come to the next step, install Laravel, where we are installing via composer, open the command line terminal, execute:

Copy the Code code as follows:
CD Sites

Sites is the root of the Web application, and you can replace it with your own root directory, and then execute:

Copy the Code code as follows:
Composer Create-project Laravel/laravel Laravel

Laravel is your app directory name, you can take a name you like. After executing the above command, wait a while (after all, at home, the speed is a big pit), after installation you will get this pile of directories:

We mainly operate models and controllers and views of these three directories: this is the composition of MVC Ah!

2. Installing bootstrap

Then the command line executes:

Copy the Code code as follows:
CD Laravel/public/packages

The laravel here corresponds to the application directory above, if you use other names when installing, please change them. Come to packages this directory after installing bootstrap, directly at the command line execution:

Copy the Code code as follows:
Bower Install Bootstrap

This is faster, and then you will get the latest stable version of Bootstrap after this download is complete. In the directory packages directory of bower_components/bootstrap/dist/here contains the bootstrap of the css,js,fonts of the three we often use in the development process of style files, JS and font files. After success you will see this:

Note: This tool is used here for Bower, which manages some front-end packages.
Here, our pre-work is ready. But before we go to the next step, we have to make sure that our Laravel/app/storage directory has the appropriate write permissions, so go back to the Laravel directory, if you have not moved the command line after installing Bower, you can directly pass:

Copy the Code code as follows:
Cd.. /.. /

Go back to the Laravel directory and then execute:

Copy the Code code as follows:
Chmod-r 755 App/storage

Once this is done, we can get into the real development phase.

3. Configure the database and build the table:

Before we start the configuration, we're going to create a database for our Laravel app, and I'll name it Laravel-start,

Then open the app/config/database.php file in the editor and fill in the corresponding database configuration items, such as:

Copy the Code code as follows:
' Default ' = ' MySQL ',
Database connection
' Connections ' = Array (
' MySQL ' = Array (
' Driver ' = ' mysql ',
' Host ' = ' 127.0.0.1 ',
' Database ' = ' Laravel-start ',
' Username ' = ' root ',
' Password ' = ',
' CharSet ' = ' utf8 ',
' Collation ' = ' utf8_unicode_ci ',
' Prefix ' = ',
),

After you have connected the database, you have to create a users table, you can create the users table directly in the database, or you can use Laravel's artisan to create the table, here we use the Laravel artisan to build tables, to understand a little bit about Laravel Migrate's knowledge. Execute the following statement:

PHP Artisan Migrate:make create-users-table
The above command will create a migrate file (the file is located in the App/database/migrations directory), the name of this file is create-users-table, Then we can create the users table by editing the migrate file that we just generated.

Copy the Code code as follows:
Public function up () {
Schema::create (' Users ', function ($table) {
$table->increments (' id ');
$table->string (' username ', 20);
$table->string (' email ', +)->unique ();
$table->string (' password ', 64);
$table->string (' Remember_token ', ()->default (' Default ');
$table->timestamps ();
});
}

The above method uses the Laravel Schema Builder class, which uses the up () method to create a users table with 5 fields: ID self-increment, username length within 20, email length of 100 and is unique, Password length of 64, Remember_token is to be more convenient when logging in, Laravel will automatically fill in the token value, but at the beginning you must set a default value, timestamp the current timestamp. One thing we need to be aware of here is that it's best to add the following code to the down () in case we need to delete the users table some day.

Copy the Code code as follows:
Public function Down ()
{
Schema::d rop (' users ');
}

After the above are done, execute the following Magic command:

Copy the Code code as follows:
PHP Artisan Migrate

There is a picture of the truth:

Finally, our prelude is finished, can formally come to Lu Laravel.

4. Start the service to try

Execute directly in the Laravel directory:

Copy the Code code as follows:
PHP Artisan Serve

Open Browser, input localhost:8000, enter, bingo!
OK, first give yourself 30 seconds of applause time, if you go to this step smoothly. Congratulations, you have entered the gate of Laravel, more surprises we one by one ...

5. Create a public view

OK, let's start now, first create a layouts folder under the App/views/folder, and then add a new PHP file under this folder, named Main.blade.php, and write the following code in this file:

Copy the Code code as follows:





Discover the beauty of Laravel 4




The Ps:layouts folder is usually used to store the function parts of the view file, such as the head of some Web pages

and tail , this is where the head is stored. Part
Is it strange to feel main.blade.php's name? Don't worry, Laravel's view file naming follows the filename.blade.php rules, because Laravel is parsed with the blade template engine, you don't have to delve into the name of the above rules to name the view file OK

To add a CSS style to a view file:

Copy the Code code as follows:





Discover the beauty of Laravel 4
{{Html::style (' Packages/bower_components/bootstrap/dist/css/bootstrap.min.css ')}}
{{Html::style (' Css/main.css ')}}




Yes, add two lines of code on top of the original main.blade.php, and then we'll create our main.css, which is mainly used to put our own defined style. Create the CSS folder under the public folder, create the Main.css file in the CSS folder, and you are done.

Add a navigation bar. Add the following code to the label of the main.blade.php file:

Copy the Code code as follows:




Laravel Novice on the road


    • {{Html::link (' users/register ', ' Register ')}}

    • {{Html::link (' users/login ', ' Login ')}}





The above just quoted some simple bootstrap class, it is not difficult, not sad.

To the basic functional part of the end, but our pursuit is not so low, so in order to better interact with the user, we hope that after the user to give some feedback, such as the success of the registration said: "Juvenile, you have successfully registered the site, congratulations XI." And so, we'll add a little bit of code to main.blade.php:

Copy the Code code as follows:

@if (Session::has (' message '))

{{session::get (' message ')}}


@endif

In order to present this feedback to the user, we have to use the Session::get (' message ') method, of course, we must first logically determine whether the message exists, so here is a simple if judgment.

In the view of the blade engine, if is used in the format

Copy the Code code as follows:
@if (conditions)
#code ...
@endif

Is this the end of it? NO, if it ends here, how are the other view files inserted between the main.blade.php? So, don't forget that there is another important thing: {{$content}}, so the code above becomes:

Copy the Code code as follows:

@if (Session::has (' message '))

{{session::get (' message ')}}


@endif
{{$content}}

{{$content}} Here is the other view file content, you can understand the other view as a string to understand, but the string is very long, and contains exactly the HTML tag. You'll see the idea below.

After creating our common view main.blade.php, let's add our CSS style to main.css:

Copy the Code code as follows:
Body {
padding-top:60px;
}
. Form-signup,. Form-signin {
margin:0 Auto;
}

Because we used in the main.blade.php file, Bootstrap's navbar height is 40px, so I set the body style to padding-top:60px, and avoid the following registration form NavBar overwrite.

Finally getting to the chase.

I rubbed it, and it took so long before I got to the point? Right, I said from here on we began to enter the Laravel controller world, do not climax so fast, better things are still behind.

6. Create Userscontroller

Come to the App/controllers folder and create the userscontroller.php file here and add the following code:

Copy the Code code as follows:
<?php
Class Userscontroller extends Basecontroller {
}
?>

Then tell us userscontroller we are going to use main.blade.php as our layouts, so:

Copy the Code code as follows:
<?php
Class Userscontroller extends Basecontroller {
protected $layout = "Layouts.main";
}
?>

This uses the path alias, you do not have to layouts/main.blade.php, you only need layouts.main,laravel will automatically help you to find layouts under the corresponding file.

7. Implement Registration

Then add the method that the user accesses when registering for our Userscontroller:

Copy the Code code as follows:
Public Function Getregister () {
$this->layout->content = View::make (' Users.register ');
}

Here we'll make the content as a users/register.blade.php file (we'll create this file), and if you're careful, you might notice: The content here is what we wrote in Main.blade.php, {$ Content}, which means that when the view is rendered, our users/register.blade.php file will be displayed for the replacement of the main.blade.php {{$content}}. Now, is it clear? Not clear yet? Feel free to contact me .... If you don't think I look ugly.

Naturally, what we have to do now is to create users/register.blade.php this file, come to the Views folder, create a new folder users/, and then in the new register.blade.php, write the following content:

Copy the Code code as follows:
{{form::open (' url ' = ' users/create ', ' class ' = ' Form-signup ')}}





Welcome to Register




{{form::open (' url ' = ' users/create ', ' class ' = ' Form-signup ')}}

      @foreach ($errors->all () as $error)
    • {{$error}}

    • @endforeach



{{Form::text (' username ', NULL, Array (' class ' + ' Form-control ', ' placeholder ' = ' user name ')}}


{{form::text (' email ', NULL, Array (' class ' = ' = ' Form-control ', ' placeholder ' + ' mailbox ')}}}


{{form::text (' password ', array (' class ' = ' Form-control ', ' placeholder ' = ' password ')}}


{{Form::text (' password_confirmation ', Array (' class ' = ' Form-control ', ' placeholder ' = ' Confirm password ')}}

{{Form::submit (' Register Now ', Array (' class ' = ' = ' btn btn-large btn-success btn-block ')}}}

{{form::close ()}}





Here we use the Laravel form class to create our registration form, first calling the open () method, representing the beginning of the creation of the form, and we also pass in the form of an array of parameters, the URL represents the table to the address of the submission, class is to represent the CSS style classes. Next we used:

Copy the Code code as follows:
@foreach ($errors->all () as $error)

  • {{$error}}

  • @endforeach

    The @foreach loop outputs the error information for each form. Because we have to allow users to register the time is always to verify that the user input data to meet the rules we set, such as the mailbox this column we stipulate that it must be the correct form of the mailbox, and if the user did not enter the correct mailbox format, we will return the error message to the user to see. That ' s it.

    What needs to be explained is how several form input boxes are created:

    Copy the Code code as follows:
    {{Form::text ()}}//Create Type=text input Box
    {{Form::p assword ()}}//Create type=password input box
    {{Form::submit ()}}//Create type=submit input box

    The value of each input box is set to NULL, because we use placeholder to better replace, the third parameter is that you can pass an array to the corresponding HTML option to implement our layout, such as the above array (' class ' = ' Form-control ', ' placeholder ' = ' Confirm password ') and so on.

    Finally, don't forget that we're going to end the form with {{Form::close ()}}.

    Here we take the registration page, the next step is to properly set up our route so that we can correctly access our Getregister () method. So, with a sacred sense of purpose, we open app/routes.php this file, the first can be inside of:

    Copy the Code code as follows:
    Route::get ('/', function ()
    {
    return view::make (' Hello ');
    });

    These lines of code kill (you can either stare or delete directly, suggest a comment), and then add the following line of code;

    Route::controller (' Users ', ' Userscontroller ');
    Notice that the first parameter is not available, and this tells us that we are following this format when we visit the Userscontroller method:

    /users/actionname
    For example we want to visit Userscontroller's Getregister (), we can enter the format in the browser address bar is:

    /users/register
    So, open your browser and enter in the Address bar:

    Http://localhost:8000/users/register
    Witness the miracle. Isn't that cool? hahaha.

    If you now add the appropriate registration information to this registration form and then click Register, you will get an unexpected error: notfoundhttpexception! that is because we have not yet written the address for the registration form: Users/create. So we naturally come to Userscontroller and add postcreate () to it:

    Copy the Code code as follows:
    Public Function PostCreate () {

    }

    So we have the address users/create correctly, but we have not yet added the appropriate conditional judgment statement, because we first want to explain here is: Getregister () and PostCreate () different, Yes, the previous get or post is the way to commit HTTP, we use the Post method in the registration form, so we use PostCreate () here.

    After explaining the above details, we have to do something very important: form validation. This is to verify the legality of the input data when the user submits the form, so that we can store the correct data in the database, which is connected to the previous one:

    Copy the Code code as follows:
    @foreach ($errors->all () as $error)

  • {{$error}}

  • @endforeach

    The $error here is the error message that we return to the user when the user input data is not valid. So, we're now adding our form validation rules to app/models/user.php (I typically put validation rules in model modal):

    Copy the Code code as follows:
    public static $rules = Array (
    ' Username ' = ' required|alpha|min:2 ',
    ' Email ' = ' required|email|unique:users ',
    ' Password ' = ' required|alpha_num|between:6,12|confirmed ',
    ' Password_confirmation ' = ' required|alpha_num|between:6,12 '
    );

    Explain what some of the above rules mean:

    Required: Required, cannot be empty
    Alpha: Letters
    Email: email format
    Unique:users: Unique, refer to the settings of the Users table
    Alpha_num: Letters or numbers
    Between: The length is between two numbers
    Confirmed: Needs to be confirmed.

    After we have the validation rules, we will refine our postcreate (), that is, to add some criteria for the user to register the user can save the registration information and further guide users to the landing page:

    Let's take one step at a minute. Geo-concept: first determine whether the user submitted data passed the verification

    Copy the Code code as follows:
    Public Function PostCreate () {
    $validator = Validator::make (Input::all (), User:: $rules);

    if ($validator->passes ()) {
    Verify that the user data is stored by
    } else {
    Show error message if validation is not passed
    }
    }
    }

    Above we get the value of table only son through Input::all (), and call User:: $rules to get the validation rules, and finally by the two in the form of parameters passed into the Validator::make () implementation validation, the following judgment statement is very clear, after the verification of what to do , and what to do without it. Clear thinking is OK.

    Then we'll refine our PostCreate () code:

    Copy the Code code as follows:
    if ($validator->passes ()) {
    $user = new user;//instantiating the user object
    $user->username = input::get (' username ');
    $user->email = input::get (' email ');
    $user->password = Hash::make (input::get (' password '));
    $user->save ();

    Return redirect::to (' Users/login ')->with (' message ', ' Welcome to registration, good play! ');
    } else {
    Show error message if validation is not passed
    }

    Above we get the value of the corresponding form input box by Input::get (' FieldName '), it is important to note that we encrypt the password, because we are all great engineers, and will not save the plaintext password like the previous csdn. So in the password column we use Hash::make () to encrypt the incoming password. We then use $user->save () to save our data to the database. After the data is saved, we use redirect::to () to jump the page to Users/login and return the successful registration information to the user via width.

    The parameter rule for redirect::to () is: Controller/action. The front is control, followed by the specific method name.
    The above is the case of validation passed, now let's look at the case where validation has not passed:

    Copy the Code code as follows:
    if ($validator->passes ()) {
    $user = new user;//instantiating the user object
    $user->username = input::get (' username ');
    $user->email = input::get (' email ');
    $user->password = Hash::make (input::get (' password '));
    $user->save ();

    Return redirect::to (' Users/login ')->with (' message ', ' Welcome to registration, good play! ');
    } else {
    Return redirect::to (' Users/register ')->with (' message ', ' please fill in the following data correctly ')->witherrors ($validator)->withinput ();
    }

    If the user does not pass the validation, I redirect it to the registration page, and pass the error message to the registration page via Witherrors ($validator), and pass the Withinput () to the registration page (which is correctly passed to the Register method, But you can understand it as well as the individual feels OK, so that we have the error message and some correct form information (without the user entering it multiple times) to improve the user experience throughout the process.

    Further, we should never forget a very important thing in our development: security. So here we need to post the form, we must ensure that it will not be csrf attack, solve this problem we need to add the following code in Userscontroller:

    Copy the Code code as follows:
    Public Function __construct () {
    $this->beforefilter (' csrf ', Array (' on ' = ' post '));
    }

    The construction method is placed in front of other methods.

    8. Implement Login

    The next step is to create the login view file, we still come to our most familiar views/users/, the new file named Login.blade.php, put the following code:

    Copy the Code code as follows:





    Welcome to Login




    {{form::open (' url ' = ' users/signin ', ' class ' = ' Form-signin ')}}


    {{form::text (' email ', NULL, Array (' class ' = ' = ' Form-control ', ' placeholder ' + ' mailbox ')}}}


    {{Form::p assword (' Password ', array (' class ' = ' Form-control ', ' placeholder ' = ' password ')}}}

    {{Form::submit (' login Now ', Array (' class ' = ' = ' btn btn-large btn-success btn-block ')}}}


    {{form::close ()}}






    Here are some important points like register.blade.php, you can look at the front if you don't understand. Then we need to define the GetLogin () method inside the Userscontroller:

    Copy the Code code as follows:
    Public Function GetLogin () {
    $this->layout->content = View::make (' Users.login ');
    }

    This is also the template for the content of the users/login.blade.php, the same as the front.
    At this time we can register a new user, if your browser is still in the http://localhost:8000/users/register you can try to enter your username, email, password to register A, of course you can also deliberately lost, see what information will be returned to you. enjoy!

    Under normal circumstances, after you sign up and then roar to the login screen (already written), but we also need to verify when logging in, if you look at the above login.blade.php, you will find that we here to the user's login form submission address set to
    ' url ' = ' users/signin ', so the next step is to add the Postsignin () method to the Userscontroller:

    Copy the Code code as follows:
    Public Function Postsignin () {
    if (auth::attempt (' email ' =>input::get (' email '), ' Password ' =>input::get (' password '))) {
    Return redirect::to (' Users/dashboard ')->with (' message ', ' welcome login ');
    } else {
    Return redirect::to (' Users/login ')->with (' message ', ' Username or password error ')->withinput ();
    }
    }

    Here we use the Auth class to verify that the information entered by the user is consistent with the information in the database, and if the validation passes, we redirect the user to Users/dashboard, and if it does not, jump back to the login page, which is almost exactly the same as when registering, I believe you can understand.

    Since it's redirected to Users/dashboard, then we'll write the Getdashboard () method, and it may not be necessary for me to say that you all know that you should add the following code to the Userscontroller:

    Copy the Code code as follows:
    Public Function Getdashboard () {
    $this->layout->content = View::make (' Users.dashboard ');
    }

    Here again, this dashboard page is usually in the login to see, in order to limit the number of people who are not logged around, we just need to add a line of code in the Userscontroller constructor:

    Copy the Code code as follows:
    Public Function __construct () {
    $this->beforefilter (' csrf ', Array (' on ' = ' post '));
    $this->beforefilter (' auth ', array (' Only ' =>array (' Getdashboard '));
    }

    Now the logic is not very clear, our next step is naturally created dashboard.blade.php file, this from Getdashboard () see we still will this view file exists views/users/directory, Let's simply write a few lines of entry-level HTML in dashboard.blade.php:

    Copy the Code code as follows:






    Welcome to the admin Panel!



    We are not able to log in here, because Auth filtering (filter) in Laravel will redirect users who are not logged on to/login by default, but we need to redirect to Users/login, so we need to customize our filter rule to open app/ filter.php, add the following code at the beginning of the code:

    Copy the Code code as follows:
    Route::filter (' auth ', function ()
    {
    if (Auth::guest ()) return redirect::guest (' Users/login ');
    });

    You are done here, if you have previously registered a user, please use your email and password to

    Http://localhost:8000/users/login

    Try logging in and you'll find: bingo!!! Log In!

    9. Implement exit

    But careful you find out no, we also have a need to improve the place ..... That's right! Is our navigation, we have logged in, it still shows login and registration, unscientific AH! So go back to the beginning of our main.blade.php in the link section we will change it to:

    Copy the Code code as follows:


        @if (! Auth::check ())
      • {{Html::link (' users/register ', ' Register ')}}

      • {{Html::link (' users/login ', ' Login ')}}
      • @else

      • {{Html::link (' users/logout ', ' Exit ')}}

      • @endif

    Yes, we add a conditional judgment statement for the navigation here, if the user does not pass Auth::check (), that is, we do not log in, we display login and registration, if logged in the display exit,

    Now that we have users/logout this link, we will think of writing this getlogout () method in Userscontroller, and this method is responsible for cleaning up the user's login information, so:

    Copy the Code code as follows:
    Public Function Getlogout () {
    if (Auth::check ())
    {
    Auth::logout ();
    }
    Return redirect::to (' Users/login ')->with (' message ', ' You are now logged out! ');
    }

    Here we auth::logout () clear the user's login information (mainly the session information), and then redirect the user to the login screen.

    10. The final final

    This little tutorial written here is basically over, I hope you have a good time to play. Finally say one more: programming is our most easy to learn the super ability, always believe that they can change the world!

  • Related Article

    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.