Skip to content

Laravel - 重定向

命名路由允许你通过特定名称引用路由,从而使你的应用更易维护。你可以使用链接到路由定义后的 name() 方法为路由分配名称。

Route::get('user/profile', function () {
// 用户个人主页逻辑
})->name('profile');

注意:在这里,我们为路由 user/profile 指定了名称“profile”。

要重定向到命名路由,你可以在 redirect() 实例上使用 route() 助手方法:

return redirect()->route('profile');

步骤 1:创建一个名为 profile_display.blade.php 的视图,并将其保存到 resources/views/profile_display.blade.php。

resources/views/profile_display.blade.php

<html>
<body>
<h1>User Profile Page (Reached via Named Route)</h1>
</body>
</html>

步骤 2:在 routes/web.php 中,为 profile_display.blade.php 视图设置路由并将其命名为 user.profile.page。同时,设置另一个路由 /go-to-profile,它将把请求重定向到命名路由 user.profile.page。

routes/web.php

Route::get('/user/actual-profile', function(){
return view('profile_display');
})->name('user.profile.page');
Route::get('/go-to-profile', function(){
return redirect()->route('user.profile.page');
});

步骤 3:访问以下 URL 来测试命名路由重定向。

http://localhost:8000/go-to-profile

步骤 4:执行上述 URL 后,你将被重定向到 http://localhost:8000/user/actual-profile,因为 /go-to-profile 路由重定向到命名路由 user.profile.page。

步骤 5:浏览器将显示 profile_display.blade.php 的内容,即“User Profile Page (Reached via Named Route)”。

你还可以重定向到控制器行为。将控制器类和行为方法名称(作为字符串或数组)传递给 action() 方法。如果你的控制器路由需要参数,你可以将它们作为第二个参数传递给 action() 方法。

// 不带参数
return redirect()->action([UserProfileController::class, 'show']);
// 带参数
return redirect()->action([PhotoController::class, 'show'], ['id' => 1]);

步骤 1:执行以下命令创建一个名为 DashboardController 的控制器。

php artisan make:controller DashboardController

步骤 2:成功执行后,你将在控制台中看到类似“控制器创建成功。”的消息。

步骤 3:将以下代码复制到文件 app/Http/Controllers/DashboardController.php 中。

app/Http/Controllers/DashboardController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index(){
return "Welcome to your Dashboard!";
}
}

步骤 4:在 routes/web.php 中添加以下行。

routes/web.php

use App\Http\Controllers\DashboardController;
// 由控制器处理的实际路由
Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard.show');
// 重定向到控制器行为的路由
Route::get('/redirect-to-dashboard', function(){
return redirect()->action([DashboardController::class, 'index']);
});

步骤 5:访问以下 URL 来测试重定向到控制器行为。

http://localhost:8000/redirect-to-dashboard

步骤 6:输出将是“Welcome to your Dashboard!”,因为请求被重定向到 DashboardController 的 index 方法。