Laravel 8 -我如何重定向/{editable_text}路由到/{user}路由



我一直在尝试创建将引导我到用户配置文件的重定向路由。重定向路由应该是来自用户数据库的字符串/文本,它应该重定向到相同的用户配置文件页面。

例如,假设我的user1有一个列名为"editable_link"值为abcd123"配置文件可以通过路由"www.mywebsite.com/user1"访问,所以当有人访问"www.mywebsite.com/abcd123"应该会重定向到"www.mywebsite.com/user1"

我已经尝试了很多方法,但没有一个适合我,因为我是新的编码。有人能给我一些最好的解决方案吗?

这是我在web.php中的内容:

<?php
use IlluminateSupportFacadesRoute;
use IlluminateSupportFacadesAuth;
use AppHttpControllersUserController;
use AppHttpControllersVisitController;
use AppHttpControllersLinkController;
use IlluminateAuthEventsVerified;
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');
});

我可以张贴你需要的任何其他代码,谢谢。

您必须首先检查包含editable_link值的路由是否在数据库中存在。所以你不能在路由定义中这样做,因为数据库还没有准备好。

检查是否存在的选项当然是通过数据库可用的地方,例如控制器或中间件。

让路线只有这一个

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

然后在UserControllershow方法中,您必须创建条件,例如,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();
}

或者,您也可以创建一个包含上述条件的中间件。

最新更新