Laravel 10自定义登录/注册未跳转到仪表板页面。

huangapple go评论68阅读模式
英文:

Laravel 10 custom login/registration not going to dashboard page

问题

我正在尝试创建自己的自定义 Laravel 10 登录/注册功能,因为我不想使用 Breez 包,我想学习如何自己制作登录/注册功能。

但我似乎无法通过仪表板页面的身份验证。我在我的仪表板函数中使用了一个 if 语句 if(Auth::check()) 来在数据库中验证用户。

但对我来说,这不起作用,因为我在从重定向回登录页面时不断收到错误消息(只有在我将新用户注册到数据库时才会发生这种情况),但每当我尝试登录时,我仍然在登录页面上获得来自我的登录函数的成功消息(请参见下面的代码)。

AuthController(仪表板):

public function dashboard(): View
{
    if(Auth::check()) {
        return view('auth.dashboard');
    }

    return view('auth.login')->with('error', 'You are not allowed to access');
}

AuthController(登录):

public function loginPost(Request $request): RedirectResponse
{
    $request->validate([
       'email' => 'required',
       'password' => 'required'
    ]);

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

    if(Auth::attempt($credentials)) {

        $request->session()->regenerate();

        return redirect()->intended(route('dashboard'))->with('success', 'You have successfully logged in');
    }

    return redirect(route('login'))->with('error', 'Oppes! You have entered invalid credentials');
}

web.php:

Route::get('/register', [AuthController::class, 'register'])->name('register');
Route::post('/register', [AuthController::class, 'registerPost'])->name('register.post');
Route::get('/login', [AuthController::class, 'login'])->name('login');
Route::post('/login', [AuthController::class, 'loginPost'])->name('login.post');
Route::get('/dashboard', [AuthController::class, 'dashboard'])->name('dashboard');
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth')->name('logout');

我尚未找到任何解决方案,所以如果有人可以帮助我,将不胜感激。

英文:

I am trying to make my own custom laravel 10 login/registration because i didn't want to use the breez package because i wanted to learn how do you make a login/registrasion by yourself.

But I cant seem to get past the authentication of the dashboard page.

I am using an if statment if(Auth::check()) on my dashboard function to authenticate the user in the database.

but for me this isn't working because i keep getting the error message from the redirect back to the login page (This only happens when I register a new user into the database) but whenever I try loging in I get the success message from my login function (See code futher down) while still being in the login page.

AuthController (Dashboard):

public function dashboard(): View
    {
        if(Auth::check()) {
            return view('auth.dashboard');
        }

        return view('auth.login')->with('error', 'You are not allowed to access');
    }

AuthController (Login):

public function loginPost(Request $request): RedirectResponse
    {
        $request->validate([
           'email' => 'required',
           'password' => 'required'
        ]);

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

        if(Auth::attempt($credentials)) {

            $request->session()->regenerate();

            return redirect()->intended(route('dashboard'))->with('success', 'You have successfully logged in');
        }

        return redirect(route('login'))->with('error', 'Oppes! You have entered invalid credentials');
    }

web.php

Route::get('/register', [AuthController::class, 'register'])->name('register');
Route::post('/register', [AuthController::class, 'registerPost'])->name('register.post');
Route::get('/login', [AuthController::class, 'login'])->name('login');
Route::post('/login', [AuthController::class, 'loginPost'])->name('login.post');
Route::get('/dashboard', [AuthController::class, 'dashboard'])->name('dashboard');
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth')->name('logout');

I havn't found any solution yet so if someone can help me it will be very appreciated.

答案1

得分: 0

你的注销功能受到中间件的保护,你还需要为仪表板路由添加一个中间件,你可以将需要身份验证中间件的路由分组。

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [AuthController::class, 'dashboard'])->name('dashboard');
    Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
});
英文:

hii your logout function is protected by middleware , you also need to add dashboard route a middleware you can group the routes that are required authentication middleware .

 Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [AuthController::class, 'dashboard'])->name('dashboard');
    Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
});

答案2

得分: 0

您的路由

Route::get('login', [FrontendAuthController::class, 'loginGet'])->name('login');
Route::post('login', [FrontendAuthController::class, 'loginPost']);
Route::post('logout', [FrontendAuthController::class, 'logout'])->name('logout');
Route::get('register', [FrontendAuthController::class, 'registerGet'])->name('register');
Route::post('register', [FrontendAuthController::class, 'registerPost']);

您的控制器:

<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;

class FrontendAuthController extends Controller
{
    public function loginGet(Request $request)
    {
        return view('front.auth.login');
    }

    public function loginPost(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ], [
            'email.required' => '邮箱字段必填。',
            'email.email' => '请输入有效的电子邮件地址。',
            'password.required' => '密码字段必填。',
        ]);

        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            return redirect()->intended('/');
        } else {
            return redirect()->back()->withErrors(['email' => '这些凭据与我们的记录不匹配。']);
        }
    }

    public function logout()
    {
        Auth::logout();
        Session::flush(); // 清除所有会话数据
        Session::regenerate(); // 重新生成会话ID
        return redirect()->route('login');
    }

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

    public function registerPost(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
        ], [
            'name.required' => '姓名字段必填。',
            'email.required' => '邮箱字段必填。',
            'email.email' => '请输入有效的电子邮件地址。',
            'email.unique' => '此电子邮件地址已注册。',
            'password.required' => '密码字段必填。',
            'password.min' => '密码必须至少包含8个字符。',
            'password.confirmed' => '密码确认不匹配。',
        ]);

        // 创建新用户记录
        $user = new User();
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->password = Hash::make($request->input('password'));
        $user->save();

        // 登录新注册的用户
        Auth::login($user);

        // 将用户重定向到主页或其他所需页面
        return redirect()->intended('/');
    }
}

您的登录视图:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登录</title>

    <link rel="stylesheet" href="{{ url('frontend/css/style.css') }}">
</head>

<body>
    <div class="main">
        <section class="signup">

            <div class="container">
                <div class="signup-content">

                    <form id="signup-form" class="signup-form" method="POST" action="{{ url('login') }}">
                        @csrf
                        <h2 class="form-title">登录</h2>
                        <div class="form-group">
                            <input type="email" class="form-input" value="{{ old('email') }}" name="email"
                                id="email" placeholder="您的电子邮件" />
                        </div>
                        <div class="form-group">
                            <input type="text" class="form-input" name="password" id="password"
                                placeholder="密码" />
                            <span toggle="#password" class="zmdi zmdi-eye field-icon toggle-password"></span>
                        </div>
                        @error('email')
                            <div style="color: red">{{ $message }}</div>
                        @enderror

                        @error('password')
                            <div style="color: red">{{ $message }}</div>
                        @enderror
                        <div class="form-group">
                            <input type="submit" name="submit" id="submit" class="form-submit" value="登录" />
                        </div>
                    </form>
                    <p class="loginhere">
                        新用户? <a href="reg-form.html" class="loginhere-link">在这里注册</a>
                    </p>
                </div>
            </div>
        </section>
    </div>
</body>

</html>

您的注册视图:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>注册</title>

    <link rel="stylesheet" href="{{ url('frontend/css/style.css') }}">
</head>

<body>
    <div class="main">
        <section class="signup">

            <div class="container">
                <div class="signup-content">

                    <form id="signup-form" class="signup-form" method="POST" action="{{ route('register') }}">
                        @csrf
                        <h2 class="form-title">注册</h2>
                        <div class="form-group">
                            <input type="text" class="form-input" value="{{ old('name') }}" name="name" id="name"
                                placeholder="您的姓名" />
                        </div>
                        <div class="form-group">
                            <input type="email" class="form-input" value="{{ old('email') }}" name="email"
                                id="email" placeholder="您的电子邮件" />
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-input" name="password" id="password"
                                placeholder="密码" />
                            <span toggle="#password" class="zmdi zmdi-eye field-icon toggle-password"></span>
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-input" name="password_confirmation"
                                id="password_confirmation" placeholder="确认密码" />
                        </div>
                        @error('name')
                            <div style="color: red">{{ $message }}</div>
                        @enderror

                        @error('email')
                            <div style="color: red">{{ $message }}</div>
                        @enderror

                        @error('password')
                            <div style="color: red">{{ $message }}</div>
                        @enderror

                        <div

<details>
<summary>英文:</summary>

Your Routes

    Route::get(&#39;login&#39;, [FrontendAuthController::class, &#39;loginGet&#39;])-&gt;name(&#39;login&#39;);
    Route::post(&#39;login&#39;, [FrontendAuthController::class, &#39;loginPost&#39;]);
    Route::post(&#39;logout&#39;, [FrontendAuthController::class, &#39;logout&#39;])-&gt;name(&#39;logout&#39;);
    Route::get(&#39;register&#39;, [FrontendAuthController::class, &#39;registerGet&#39;])-&gt;name(&#39;register&#39;);
    Route::post(&#39;register&#39;, [FrontendAuthController::class, &#39;registerPost&#39;]);

 

   
Your controller :

    &lt;?php
    
    namespace App\Http\Controllers\Frontend;
    
    use App\Http\Controllers\Controller;
    use App\Models\User;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Facades\Session;
    
    class FrontendAuthController extends Controller
    {
        public function loginGet(Request $request)
        {
            return view(&#39;front.auth.login&#39;);
        }
    
        public function loginPost(Request $request)
        {
            $request-&gt;validate([
                &#39;email&#39; =&gt; &#39;required|email&#39;,
                &#39;password&#39; =&gt; &#39;required&#39;,
            ], [
                &#39;email.required&#39; =&gt; &#39;The email field is required.&#39;,
                &#39;email.email&#39; =&gt; &#39;Please enter a valid email address.&#39;,
                &#39;password.required&#39; =&gt; &#39;The password field is required.&#39;,
            ]);
    
            $credentials = $request-&gt;only(&#39;email&#39;, &#39;password&#39;);
            if (Auth::attempt($credentials)) {
                return redirect()-&gt;intended(&#39;/&#39;);
            } else {
                return redirect()-&gt;back()-&gt;withErrors([&#39;email&#39; =&gt; &#39;These credentials do not match our records.&#39;]);
            }
        }
    
        public function logout()
        {
            Auth::logout();
            Session::flush(); // Clear all session data
            Session::regenerate(); // Regenerate the session ID
            return redirect()-&gt;route(&#39;login&#39;);
        }
    
        public function registerGet()
        {
            return view(&#39;front.auth.register&#39;);
        }
    
        public function registerPost(Request $request)
        {
            $request-&gt;validate([
                &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,
                &#39;email&#39; =&gt; &#39;required|email|unique:users,email&#39;,
                &#39;password&#39; =&gt; &#39;required|min:8|confirmed&#39;,
            ], [
                &#39;name.required&#39; =&gt; &#39;The name field is required.&#39;,
                &#39;email.required&#39; =&gt; &#39;The email field is required.&#39;,
                &#39;email.email&#39; =&gt; &#39;Please enter a valid email address.&#39;,
                &#39;email.unique&#39; =&gt; &#39;This email address is already registered.&#39;,
                &#39;password.required&#39; =&gt; &#39;The password field is required.&#39;,
                &#39;password.min&#39; =&gt; &#39;The password must be at least 8 characters.&#39;,
                &#39;password.confirmed&#39; =&gt; &#39;The password confirmation does not match.&#39;,
            ]);
    
            // Create a new user record
            $user = new User();
            $user-&gt;name = $request-&gt;input(&#39;name&#39;);
            $user-&gt;email = $request-&gt;input(&#39;email&#39;);
            $user-&gt;password = Hash::make($request-&gt;input(&#39;password&#39;));
            $user-&gt;save();
    
            // Log in the newly registered user
            Auth::login($user);
    
            // Redirect the user to the home page or any other desired page
            return redirect()-&gt;intended(&#39;/&#39;);
        }
    }

Your Login blade 

    &lt;!DOCTYPE html&gt;
    &lt;html&gt;
    
    &lt;head&gt;
        &lt;meta charset=&quot;UTF-8&quot;&gt;
        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;
        &lt;title&gt;Sign In&lt;/title&gt;
    
        &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url(&#39;frontend/css/style.css&#39;) }}&quot;&gt;
    &lt;/head&gt;
    
    &lt;body&gt;
        &lt;div class=&quot;main&quot;&gt;
            &lt;section class=&quot;signup&quot;&gt;
    
                &lt;div class=&quot;container&quot;&gt;
                    &lt;div class=&quot;signup-content&quot;&gt;
    
                        &lt;form id=&quot;signup-form&quot; class=&quot;signup-form&quot; method=&quot;POST&quot; action=&quot;{{ url(&#39;login&#39;) }}&quot;&gt;
                            @csrf
                            &lt;!--	&lt;img src=&quot;images/logo.svg&quot; alt=&quot;&quot;&gt;--&gt;
                            &lt;h2 class=&quot;form-title&quot;&gt;Login Here&lt;/h2&gt;
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;email&quot; class=&quot;form-input&quot; value=&quot;{{ old(&#39;email&#39;) }}&quot; name=&quot;email&quot;
                                    id=&quot;email&quot; placeholder=&quot;Your Email&quot; /&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;text&quot; class=&quot;form-input&quot; name=&quot;password&quot; id=&quot;password&quot;
                                    placeholder=&quot;Password&quot; /&gt;
                                &lt;span toggle=&quot;#password&quot; class=&quot;zmdi zmdi-eye field-icon toggle-password&quot;&gt;&lt;/span&gt;
                            &lt;/div&gt;
                            @error(&#39;email&#39;)
                                &lt;div style=&quot;color: red&quot;&gt;{{ $message }}&lt;/div&gt;
                            @enderror
    
                            @error(&#39;password&#39;)
                                &lt;div style=&quot;color: red&quot;&gt;{{ $message }}&lt;/div&gt;
                            @enderror
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;submit&quot; name=&quot;submit&quot; id=&quot;submit&quot; class=&quot;form-submit&quot; value=&quot;Sign in&quot; /&gt;
                            &lt;/div&gt;
                        &lt;/form&gt;
                        &lt;p class=&quot;loginhere&quot;&gt;
                            New User? &lt;a href=&quot;reg-form.html&quot; class=&quot;loginhere-link&quot;&gt;Register here&lt;/a&gt;
                        &lt;/p&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/section&gt;
        &lt;/div&gt;
    &lt;/body&gt;
    
    &lt;/html&gt;


Your Register page

    &lt;!DOCTYPE html&gt;
    &lt;html&gt;
    
    &lt;head&gt;
        &lt;meta charset=&quot;UTF-8&quot;&gt;
        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
        &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;
        &lt;title&gt;Register&lt;/title&gt;
    
        &lt;link rel=&quot;stylesheet&quot; href=&quot;{{ url(&#39;frontend/css/style.css&#39;) }}&quot;&gt;
    &lt;/head&gt;
    
    &lt;body&gt;
        &lt;div class=&quot;main&quot;&gt;
            &lt;section class=&quot;signup&quot;&gt;
    
                &lt;div class=&quot;container&quot;&gt;
                    &lt;div class=&quot;signup-content&quot;&gt;
    
                        &lt;form id=&quot;signup-form&quot; class=&quot;signup-form&quot; method=&quot;POST&quot; action=&quot;{{ route(&#39;register&#39;) }}&quot;&gt;
                            @csrf
                            &lt;h2 class=&quot;form-title&quot;&gt;Register Here&lt;/h2&gt;
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;text&quot; class=&quot;form-input&quot; value=&quot;{{ old(&#39;name&#39;) }}&quot; name=&quot;name&quot; id=&quot;name&quot;
                                    placeholder=&quot;Your Name&quot; /&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;email&quot; class=&quot;form-input&quot; value=&quot;{{ old(&#39;email&#39;) }}&quot; name=&quot;email&quot;
                                    id=&quot;email&quot; placeholder=&quot;Your Email&quot; /&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;password&quot; class=&quot;form-input&quot; name=&quot;password&quot; id=&quot;password&quot;
                                    placeholder=&quot;Password&quot; /&gt;
                                &lt;span toggle=&quot;#password&quot; class=&quot;zmdi zmdi-eye field-icon toggle-password&quot;&gt;&lt;/span&gt;
                            &lt;/div&gt;
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;password&quot; class=&quot;form-input&quot; name=&quot;password_confirmation&quot;
                                    id=&quot;password_confirmation&quot; placeholder=&quot;Confirm Password&quot; /&gt;
                            &lt;/div&gt;
                            @error(&#39;name&#39;)
                                &lt;div style=&quot;color: red&quot;&gt;{{ $message }}&lt;/div&gt;
                            @enderror
    
                            @error(&#39;email&#39;)
                                &lt;div style=&quot;color: red&quot;&gt;{{ $message }}&lt;/div&gt;
                            @enderror
    
                            @error(&#39;password&#39;)
                                &lt;div style=&quot;color: red&quot;&gt;{{ $message }}&lt;/div&gt;
                            @enderror
    
                            &lt;div class=&quot;form-group&quot;&gt;
                                &lt;input type=&quot;submit&quot; name=&quot;submit&quot; id=&quot;submit&quot; class=&quot;form-submit&quot; value=&quot;Register&quot; /&gt;
                            &lt;/div&gt;
                        &lt;/form&gt;
                        &lt;p class=&quot;loginhere&quot;&gt;
                            Already have an account? &lt;a href=&quot;{{ route(&#39;login&#39;) }}&quot; class=&quot;loginhere-link&quot;&gt;Login here&lt;/a&gt;
                        &lt;/p&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/section&gt;
        &lt;/div&gt;
    &lt;/body&gt;
    
    &lt;/html&gt;




I think This will solve your all queries


</details>



huangapple
  • 本文由 发表于 2023年7月17日 17:26:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定