search
HomePHP FrameworkLaravellaravel implements login registration

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 标记。

@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>

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

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

@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>

注意,我们使用了 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
Laravel's Impact: Simplifying Web DevelopmentLaravel's Impact: Simplifying Web DevelopmentApr 21, 2025 am 12:18 AM

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravel: Frontend or Backend? Clarifying the Framework's RoleLaravel: Frontend or Backend? Clarifying the Framework's RoleApr 21, 2025 am 12:17 AM

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel vs. Python: Exploring Performance and ScalabilityLaravel vs. Python: Exploring Performance and ScalabilityApr 21, 2025 am 12:16 AM

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel vs. Python (with Frameworks): A Comparative AnalysisLaravel vs. Python (with Frameworks): A Comparative AnalysisApr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Frontend with Laravel: Exploring the PossibilitiesFrontend with Laravel: Exploring the PossibilitiesApr 20, 2025 am 12:19 AM

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel: Building Server-Side ApplicationsPHP and Laravel: Building Server-Side ApplicationsApr 20, 2025 am 12:17 AM

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel vs. Python: The Learning Curves and Ease of UseLaravel vs. Python: The Learning Curves and Ease of UseApr 20, 2025 am 12:17 AM

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's Strengths: Backend DevelopmentLaravel's Strengths: Backend DevelopmentApr 20, 2025 am 12:16 AM

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!