Home  >  Article  >  PHP Framework  >  Examples to explain how Laravel implements login and registration functions

Examples to explain how Laravel implements login and registration functions

PHPz
PHPzOriginal
2023-04-12 09:23:392206browse

Laravel is a very popular PHP framework. It has the advantages of simplicity, ease of use, efficiency, stability, safety and reliability, and is widely used in the development of web applications. In web application development, login and registration functions are essential, so how to use Laravel to implement login and registration functions? This article will introduce it to you in detail.

1. Install Laravel

Before using Laravel to develop, you need to install Laravel first. You can install it through composer and use the following command:

composer create-project --prefer-dist laravel/laravel project_name

After the installation is completed, enter the directory where the project is located. Execute the following command to start the Laravel service:

php artisan serve

2. Create user model and data table

In Laravel, you can easily use Eloquent ORM to handle database operations. We need to create user model and data table.

  1. Create user model

It is very convenient to create a model in Laravel. You only need to use the following command in the command line:

php artisan make:model User

In app A User.php file will be generated in the directory, which is the user model. Laravel will set the table name to the plural of the model by default, so we need to set the table name in the User model, as follows:

class User extends Model
{
    protected $table = 'users';
}

2. Create users data table

Create in the database users table, run the following command to create a migration:

php artisan make:migration create_users_table --create=users

A migration file will be generated in the database/migrations directory, as shown below:

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Execute the following command to generate a data table:

php artisan migrate

3. Use the laravel/ui package to create user authentication

Laravel provides a laravel/ui package that can be used to create a user authentication system. First use the following command to install the laravel/ui package:

composer require laravel/ui

After the installation is completed, execute the following command to create the user authentication system:

php artisan ui vue --auth

The function of this command is to create the Vue.js front-end framework Default login and registration views. After the execution is completed, you will find that there is an auth folder in the resources/views directory, including two view files auth/login.blade.php and auth/register.blade.php.

4. Set routing

In Laravel, routing is a mechanism that binds URLs to controller methods. We need to set up routing so that we can access the login and registration pages.

In the routes/web.php file, add the following route definition:

Route::get('/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('/login', 'Auth\LoginController@login');
Route::get('/register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('/register', 'Auth\RegisterController@register');

These routes will call the methods in Laravel's default Auth\LoginController and Auth\RegisterController respectively.

5. Customized user authentication

In practical applications, we often need to customize user authentication to meet business needs. The following are the steps to customize user authentication:

  1. Create LoginController and RegisterController controllers

We need to create LoginController and RegisterController controls in the app/Http/Controllers/Auth directory controller, the code is as follows:

class LoginController extends Controller
{
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);
    }

    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            return redirect('/login')
                        ->withErrors($validator)
                        ->withInput();
        }

        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            return redirect('/');
        } else {
            return redirect('/login')
                        ->withErrors(['email' => '邮箱或密码错误'])
                        ->withInput();
        }
    }
}
class RegisterController extends Controller
{
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);
    }

    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            return redirect('/register')
                        ->withErrors($validator)
                        ->withInput();
        }

        $user = User::create([
            'name' => $request['name'],
            'email' => $request['email'],
            'password' => bcrypt($request['password']),
        ]);

        Auth::login($user);
        
        return redirect('/');
    }
}

In the custom controller, the validator method is used to verify the legitimacy of the user input data and handle errors during the login or registration process.

  1. Modify routing

Modify the original routing to the following code:

Route::get('/login', 'LoginController@showLoginForm')->name('login');
Route::post('/login', 'LoginController@login');
Route::get('/register', 'RegisterController@showRegistrationForm')->name('register');
Route::post('/register', 'RegisterController@register');

In this way, the code is modified and written according to our own needs , just log in and register.

6. Summary

This article introduces in detail the steps to use Laravel to implement user login and registration, including creating user models and data tables, using the laravel/ui package to create a default user authentication system, and setting routing and custom user authentication. Whether it is the basic version or the customized version, using Laravel is very convenient, and development efficiency has also been greatly improved. If you are a PHP developer, you might as well try Laravel.

The above is the detailed content of Examples to explain how Laravel implements login and registration functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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