Laravel 8 - 如何將 /{editable_text} 路由重新導向到 /{user} 路由
P粉986028039
P粉986028039 2024-04-06 17:26:11
0
1
394

我一直在嘗試建立重定向路由來引導我存取用戶個人資料。重定向路由應該是來自使用者資料庫的字串/文本,並且應該重定向到相同的使用者個人資料頁面。

例如,假設我的user1 有一個名為“editable_link”的列,其值為“abcd123”,並且可以透過路由“www.mywebsite.com/user1”存取設定文件,因此當有人造訪“www.mywebsite. com/”時abcd123”,它應該將他重定向到“www.mywebsite.com/user1”。

我嘗試了很多方法,但沒有任何方法對我有用,因為我是編碼新手。有人可以給我一些最好的解決方案嗎?

這是我的 web.php 中的內容:

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\UserController;
use App\Http\Controllers\VisitController;
use App\Http\Controllers\LinkController;
use Illuminate\Auth\Events\Verified;

Route::get('/', function () {
    return view('welcome');
});
Route::get('/verified', function () {
    return view('verified');
});

Auth::routes(['verify' => true]);

Route::group(['middleware' => 'auth', 'prefix' => 'dashboard', ], function() {

    Route::get('/links', [LinkController::class, 'index']);
    Route::get('/links/new', [LinkController::class, 'create'])->middleware('verified');
    Route::post('/links/new', [LinkController::class, 'store']);
    Route::get('/links/{link}', [LinkController::class, 'edit']);
    Route::post('/links/{link}', [LinkController::class, 'update']);
    Route::delete('/links/{link}', [LinkController::class, 'destroy']);
    Route::get('/qr', [LinkController::class, 'qr']);

    Route::get('/settings', [UserController::class, 'settings']);
    Route::get('/settings/edit', [UserController::class, 'edit']);
    Route::get('/settings/profile', [UserController::class, 'profile']);
    Route::get('/settings/help', [UserController::class, 'help']);
    Route::post('/settings/edit', [UserController::class, 'update']);
    Route::post('/settings/profile', [UserController::class, 'update_avatar']);

});

Route::post('/visit/{link}', [VisitController::class, 'store']);
Route::get('/{user}', [UserController::class, 'show'])->name('show');

這就是我想要創建的:

Route::get('/qr/{editable_link}', function () {
    return redirect('{user}');
Route::get('/{user}', [UserController::class, 'show'])->name('show');
});

我可以發布您需要的任何其他程式碼,謝謝。

P粉986028039
P粉986028039

全部回覆(1)
P粉041856955

您必須先檢查資料庫中是否存在包含 editable_link 值的路由。那麼你就不能在路由定義中執行此操作,因為那裡的資料庫尚未準備好。

當然,您可以選擇透過資料庫可用的地方(例如控制器或中間件)來檢查是否存在。

讓路由只有這條

Route::get('/{user}', [UserController::class, 'show'])->name('show');

然後在 UserController show 方法中,您必須建立條件,例如 example

public function show($user)
{
    // checks if $user parameter is an editable_link that exist in db
    $userWithEditableLink = User::where('editable_link', $user)->first();
    
    // redirect if above exist to the same route but with, for example, username
    if ($userWithEditableLink) {
        return redirect($userWithEditableLink->username);
    }
    
    // do something as, such as
    // $user = User::where('username', $user)->firstOrFail();
}

或者,您可以建立一個也包含上述條件的中間件。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!