ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] # URL ## 基础 ``` // 生成基础 URL $post = App\Post::find(1); echo url("/posts/{$post->id}"); // http://example.com/posts/1 // 访问当前 URL echo url()->current(); //不包含查询参数 echo url()->full(); //包含查询参数 echo url()->previous(); //上一个请求连接,包含查询参数 // 通过 URL facade 访问 use Illuminate\Support\Facades\URL; echo URL::current(); ``` ## 命名路由的 URL 辅助函数`route`使用命名路由生成 URL,不与路由上定义的 URL 相耦合。 ``` Route::get('/post/{post}', function () { // 单个参数 })->name('post.show'); echo route('post.show', ['post' => 1]); // http://example.com/post/1 Route::get('/post/{post}/comment/{comment}', function () { // 多个参数 })->name('comment.show'); echo route('comment.show', ['post' => 1, 'comment' => 3]); // http://example.com/post/1/comment/3 // 使用 Eloquent 模型 的主键生成 URL,自动提取模型的主键 echo route('post.show', ['post' => $post]); ``` ### 签名 URL ``` // http://test.com/unsubscribe/1?signature=签名 use Illuminate\Support\Facades\URL; return URL::signedRoute('unsubscribe', ['user' => 1]); // 设置有效期 // http://test.com/unsubscribe/1?expires=1608476953&signature=签名 return URL::signedRoute('unsubscribe', ['user' => 1], now()->addMinutes(30)); // 使用 temporarySignedRoute 方法 return URL::temporarySignedRoute( 'unsubscribe', now()->addMinutes(30), ['user' => 1] ); ``` ### 验证签名路由请求 一、Request 验证 ``` use Illuminate\Http\Request; Route::get('/unsubscribe/{user}', function (Request $request) { if (! $request->hasValidSignature()) { abort(401); } // ... })->name('unsubscribe'); ``` 二、中间件验证 ``` // 在 app/Http/Kernel.php 中的 $routeMiddleware 属性中增加中间件,默认已存在 protected $routeMiddleware = [ // ... 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, ]; // 验证失败返回403错误响应 Route::post('/unsubscribe/{user}', function (Request $request) { // ... })->name('unsubscribe')->middleware('signed'); ``` ## 控制器行为的 URL ``` $url = action('HomeController@index'); use App\Http\Controllers\HomeController; $url = action([HomeController::class, 'index']); // 传递参数 $url = action('UserController@profile', ['id' => 1]); ``` ## 默认值 [参考文章](https://learnku.com/articles/43638) ``` // 定义路由 Route::get('/{locale}/posts', 'IndexController@posts')->name('posts'); // 定义中间件 <?php namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\URL; class SetDefaultLocaleForUrls { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { URL::defaults(['locale' => $request->user()->locale ?? 'cn']); return $next($request); } } // 注册中间件,在 app/Http/Kernel.php 中的 $routeMiddleware 属性中增加中间件 protected $routeMiddleware = [ // ... 'locale' => \App\Http\Middleware\SetDefaultLocaleForUrls::class, ]; // 在路由或控制器中配置中间件 Route::get('/', 'IndexController@index')->middleware('locale'); public function __construct() { $this->middleware('locale')->only('index'); } // 在控制器中使用,不需要设置 locale 参数 // http://test.com/cn/posts public function index() { return route('posts'); } ```