Home  >  Article  >  PHP Framework  >  laravel implements login registration

laravel implements login registration

WBOY
WBOYOriginal
2023-05-20 21:10:10937browse

Laravel is a popular PHP framework that provides a powerful development environment that allows you to build web applications more easily. One of the important features is Laravel's own authentication system, which allows you to quickly implement user authentication, including login and registration. In this article, we will demonstrate how to implement login registration using Laravel.

Deployment environment
Before we start implementing authentication, we need to ensure that the Laravel environment has been configured and the database connection has been configured. If you haven't installed Laravel yet, you can refer to the installation guide in the official documentation. In the Laravel application, we create the necessary file and directory structure using the Artisan command line tool. From the command line, we can create a new Laravel application using the following command:

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

After creating, navigate to the application's In the root directory, run the following command to generate the application key:

php artisan key:generate

Register route
In Laravel, routing is the bridge connecting URIs and corresponding controller methods. To register our authentication routes, we need to update the routes/web.php file. In this file, we define the routes for the application, which include the login and registration routes.

First, we need to define a route that sends a POST request to /register and bind it to the register() method of RegisterController. This will render a registration form where the user can fill in their username and password.

Route::post('/register', 'AuthRegisterController@register')->name('register');

Next, we need to define the POST request to be sent to /login route and bind it to the LoginController's login() method. This will render a login form where the user can fill in their login name and password. If the user does not have valid credentials to authenticate, the application redirects to the login form.

Route::post('/login', 'AuthLoginController@login')->name('login');

Finally, we need to define all protected routes. In Laravel, we can use the auth middleware to ensure that the user has been authenticated. This middleware will automatically redirect unauthenticated users to the /login route.

Route::middleware(['auth'])->group(function () {

// your protected routes go here

});

Handling Controller
We have The necessary routes are defined, now they need to be handled in the controller. In Laravel, controllers are classes that handle specific HTTP requests, and methods in the controller return HTTP responses. In the application, we need to create two controllers to handle registration and login requests.

In the app/Http/Controllers/Auth directory, create two files, LoginController.php and RegisterController.php. These two files are the controller classes that come with Laravel. In these controllers, we need to override Laravel's default methods to provide custom functionality for login and registration requests.

Login Controller
Let’s first look at the LoginController.php controller. This controller contains two methods: showLoginForm() and login().

The showLoginForm() method returns the login form view (resources/views/auth/login.blade.php), which contains a form where the user can enter their login name and password. This method is provided by Laravel.

public function showLoginForm()
{

return view('auth.login');

}

login() method is where the login logic is actually implemented. This method receives an IlluminateHttpRequest instance and validates user input using the instance's validate() method. If the form validation is successful, Laravel will automatically search for the user with the given login and password and log them into the application.

public function login(Request $request)
{

$request->validate([
    'email' => 'required|string|email',
    'password' => 'required|string',
    'remember' => 'boolean'
]);

$credentials = $request->only('email', 'password');

if (Auth::attempt($credentials, $request->remember)) {
    return redirect()->intended('dashboard');
}

return redirect()->back()->withInput($request->only('email', 'remember'));

}

Note that the attempt() method will automatically check whether the password is correct based on the given credentials . If the password is incorrect, false will be returned.

If the user has successfully authenticated and the URL they previously requested is stored (usually a URL blocked by auth middleware), we can use the Laravel helper function intended() to redirect them to that URL. . If no URL is stored, redirect to the front-end dashboard (/dashboard).

Register Controller
Next let’s look at the RegisterController.php controller. In addition to Laravel's default methods, we also need to implement the register() method.

The register() method is very similar to the login() method. It receives an IlluminateHttpRequest instance and validates user input using the instance's validate() method. If the form validation is successful, Laravel will create a new user and save it to the database. We can then use Laravel's default behavior to log the user into the application.

public function register(Request $request)
{

$request->validate([
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:users',
    'password' => 'required|string|min:6|confirmed',
]);

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

Auth::login($user);

return redirect()->intended('dashboard');

}

In the registration controller we can use the Hash auxiliary function to encrypt the password. If the password verification is successful, we create the new user and log him into the application.

View Layer
Now that we have defined the necessary routes and controllers, we need to create the authentication view.

在 resources/views/auth 目录中,我们可以创建 login.blade.php 和 register.blade.php 两个视图文件。这些视图包含登录和注册表单,使用了一些 Laravel 帮助程序,可以处理表单验证并显示错误消息。

登录视图
在 login.blade.php 文件中,我们可以使用 Laravel 的 Form 辅助函数创建登录表单。这个函数会自动为表单添加 CSRF 令牌,并为输入字段编写 HTML 标记。

71085032ff00cb55c43cd8d91e1cd1ac

@csrf

<div class="form-group row">
    <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('Email Address') }}</label>

    <div class="col-md-6">
        <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>

        @if ($errors->has('email'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('email') }}</strong>
            </span>
        @endif
    </div>
</div>

<div class="form-group row">
    <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

    <div class="col-md-6">
        <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

        @if ($errors->has('password'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('password') }}</strong>
            </span>
        @endif
    </div>
</div>

<div class="form-group row">
    <div class="col-md-6 offset-md-4">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

            <label class="form-check-label" for="remember">
                {{ __('Remember Me') }}
            </label>
        </div>
    </div>
</div>

<div class="form-group row mb-0">
    <div class="col-md-8 offset-md-4">
        <button type="submit" class="btn btn-primary">
            {{ __('Login') }}
        </button>

        @if (Route::has('password.request'))
            <a class="btn btn-link" href="{{ route('password.request') }}">
                {{ __('Forgot Your Password?') }}
            </a>
        @endif
    </div>
</div>

f5a47148e367a6035fd7a2faa965022e

注意,我们使用了 Blade 模板引擎的 @csrf 和 @if 语句来生成必要的 CSRF 令牌并显示验证错误。

注册视图
在 register.blade.php 文件中,我们可以使用 Laravel 的 Form 帮助器创建注册表单。这个函数自动为表单添加 CSRF 令牌,并为输入字段编写 HTML 标记。

b42125e3aba3ade041a95113cf783d0b

@csrf

<div class="form-group row">
    <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>

    <div class="col-md-6">
        <input id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" name="name" value="{{ old('name') }}" required autofocus>

        @if ($errors->has('name'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('name') }}</strong>
            </span>
        @endif
    </div>
</div>

<div class="form-group row">
    <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

    <div class="col-md-6">
        <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>

        @if ($errors->has('email'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('email') }}</strong>
            </span>
        @endif
    </div>
</div>

<div class="form-group row">
    <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

    <div class="col-md-6">
        <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

        @if ($errors->has('password'))
            <span class="invalid-feedback" role="alert">
                <strong>{{ $errors->first('password') }}</strong>
            </span>
        @endif
    </div>
</div>

<div class="form-group row">
    <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>

    <div class="col-md-6">
        <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
    </div>
</div>

<div class="form-group row mb-0">
    <div class="col-md-6 offset-md-4">
        <button type="submit" class="btn btn-primary">
            {{ __('Register') }}
        </button>
    </div>
</div>

f5a47148e367a6035fd7a2faa965022e

注意,我们使用了 Blade 模板引擎的 @csrf 和 @if 语句来生成必要的 CSRF 令牌并显示验证错误消息。

结论
通过 Laravel 可以快速、方便、安全地实现 Web 应用程序的登录和注册身份验证功能,从而保护您的应用程序免受未授权的访问。在本文中,我们介绍了 Laravel 的身份验证系统并实现了注册和登录。现在,您可以使用这些基础知识构建更完整的用户身份验证系统,或将其集成到您的现有应用程序中。

The above is the detailed content of laravel implements login registration. 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