Trong thư viện laravel/ui, thì chức năng password reset dù cho token có hết hạn thì vẫn có truy cập vào trang password reset, đến khi bạn submit form thì mới thông báo là token đã hết hạn. Nhưng có một số dự án, thì người người ta muốn chuyển đến trang password expire chẳng hạn chứ không muốn người dùng submit form thì mới thông báo lỗi.

Trong bài viết này, tôi sẽ hướng dẫn các bạn chuyển hướng đến trang password expire khi token hết hạn.

Đầu tiên, chúng ta mở thư mục resources\views\auth\passwords và tạo một file có tên là expired.blade.php và có nội dung như sau:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Password Reset') }}</div>

                <div class="card-body">
                    {{ __('Link reset password has expired. Please try again.') }}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Bạn mở file ResetPasswordController.php nằm trong thư mục app\Http\Controllers\Auth và chỉnh sửa như sau:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Display the password expired view.
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function expired()
    {
        return view('auth.passwords.expired');
    }
}

Tiếp theo, bạn mở file web.php nằm trong thư mục routes và thêm dòng bên dưới:

Route::get('/passwords/expired', [App\Http\Controllers\Auth\ResetPasswordController::class, 'expired'])->name('passwords.expired');

Tiếp theo, chúng ta thực hiện chuyển hướng đến URL /passwords/expired nếu như token đã hết hạn sử dụng, bạn hãy mở file ResetPasswordController.php nằm trong thư mục app\Http\Controllers\Auth và chỉnh sửa như sau:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Http\Request;
use Carbon\Carbon;
use DB;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    public function __construct(HasherContract $hasher)
    {
        $this->hasher = $hasher;
    }

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $token
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showResetForm(Request $request, $token = null)
    {
        $password_reset = DB::table("password_resets")->where('email', $request->email)->first();

        if($password_reset && $token && $request->email && !$this->tokenExpired($password_reset->created_at) && $this->hasher->check($token, $password_reset->token) ) {
            return view('auth.passwords.reset')->with(['token' => $token, 'email' => $request->email]);
        }

        return redirect()->route('passwords.expired');
    }

    /**
     * Determine if the token has expired.
     *
     * @param  string  $createdAt
     * @return bool
     */
    protected function tokenExpired($createdAt)
    {
        return Carbon::parse($createdAt)->addMinutes(config('auth.passwords.users.expire'))->isPast();
    }

    /**
     * Display the password expired view.
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function expired()
    {
        return view('auth.passwords.expired');
    }
}

Khi bạn truy cập trang URL password reset mà token hết hạn, nó sẽ chuyển hướng đến trang password expired và thông báo người dùng link đã không còn sử dụng được. Tôi hy vọng bạn thích hướng dẫn này. Nếu bạn có bất kỳ câu hỏi nào hãy liên hệ với chúng tôi qua trang contact. Cảm ơn bạn.

CÓ THỂ BẠN QUAN TÂM

Laravel Many to Many Polymorphic Relationship

Laravel Many to Many Polymorphic Relationship

Many to many Polymorphic Relationship cũng hơi phức tạp để hiểu. Ví dụ: nếu bạn có bài post, video và tag, bạn cần kết nối với nhau theo yêu cầu là mọi bài đăng đều có nhiều tag và video cũng như vậy....

Efficient Laravel PDF Export for Large Datasets

Efficient Laravel PDF Export for Large Datasets

Xuất file PDF là một tính năng quan trọng của nhiều ứng dụng web, đặc biệt là các trang thương mại điện tử, giúp người dùng tạo và lưu trữ các bản báo cáo, hóa đơn, v.v.  Tuy nhiên, khi phải xử lý...

Integrating TinyMCE in Laravel 10 using Vite

Integrating TinyMCE in Laravel 10 using Vite

TinyMCE TinyMCE là một trình soạn thảo WYSIWYG được xây dựng trên nền tảng Javascript, được phát triển dưới dạng mã nguồn mở theo giấy phép MIT bởi Tiny Technologies Inc. TinyMCE cho phép ngư...

Integrating elFinder into TinyMCE 6 in Laravel

Integrating elFinder into TinyMCE 6 in Laravel

TinyMCE TinyMCE là một trình soạn thảo WYSIWYG được xây dựng trên nền tảng Javascript, được phát triển dưới dạng mã nguồn mở theo giấy phép MIT bởi Tiny Technologies Inc. TinyMCE cho phép người d...

Integrating OpenAI in Laravel

Integrating OpenAI in Laravel

OpenAI OpenAI là một phòng thí nghiệm nghiên cứu trí tuệ nhân tạo (AI) của Mỹ bao gồm tổ chức phi lợi nhuận OpenAI Incorporated (OpenAI Inc.) và công ty con hoạt động vì lợi nhuận OpenAI Limited Par...

Laravel Validate Video Duration

Laravel Validate Video Duration

Đôi khi trong dự án, chúng ta cần xác định thời lượng video được phép upload lên server. Nhưng rất tiếc, Laravel không cung cấp validate xác định thời lượng video để chúng ta thực hiện được. Vì vậy, t...

ZSH-Artisan CLI and Docker: The Perfect Match for Laravel Development

ZSH-Artisan CLI and Docker: The Perfect Match for Laravel Development

Zsh Zsh viết tắt của “ Z Shell ” là một shell nâng cao cho hệ thống Unix và Linux. Nó được phát triển nhằm cung cấp các tính năng và khả năng cao hơn so với shell mặc định trên hầu hết các hệ thố...

How To Optimize Your Site With GZIP Compression

How To Optimize Your Site With GZIP Compression

GZIP là công nghệ nén thường được sử dụng để truyền dữ liệu một cách nhanh chóng qua Insternet. Hiện nay, GZIP là một tiêu chuẩn để nén các file trên trang web, đa số các website hiện nay hơn 99% sử d...

Laravel Routing

Laravel Routing

Route là gì? Đúng như tên gọi của nó, Route thực hiện chức năng định tuyến, dẫn đường cho các HTTP request gửi đến đúng nơi mà ta mong muốn. Với sự phát triển mạnh mẽ của ứng dụng web ngày nay, việc...

ManhDanBlogs