将全局变量从当前 url 传递到 laravel 组路由
Pass global variable to laravel group route from current url
我有一个具有这种结构的路由组:
Route::prefix('admin/{w_id}')->middleware(['auth'])->as('weblog.')->group(function () {
Route::get('/dashboard', [HomePageController::class, 'index'])->name('dashboard');
Route::resource('/blogcategory', CategoryController::class);
});
在仪表板路线上,我在 url 中有 w_id,当我想将用户重定向到 blogcategory 路线(从任何地方)时,我应该在路线助手 [=29] 中手动传递 w_id =],我需要从当前 link.
全局设置一些东西
例如当我使用这个方法时:
'route' => 'weblog.blogcategory.store'
我收到如下错误:
Missing required parameters for [Route: weblog.blogcategory.store]
我应该手动将 w_id 参数传递给所有路由助手,我需要从页面的当前 url 全局设置 w_id。
我正在为用户的博客开发完全独立的管理区域,并且所有 url.
中都存在博客 ID
为了避免再次传递 w_id,您需要使用 URL::defaults()
,它会为您的参数创建一个默认值。
您可以使用中间件来传递默认值。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultWidForWeblogs
{
public function handle($request, Closure $next)
{
URL::defaults(['w_id' => /* pass the default value here*/]);
return $next($request);
}
}
现在在app/Http/Kernel.php
中注册中间件class(查看更多说明here)
protected $routeMiddleware = [
...
'pass_wid' => \App\Http\Middleware\SetDefaultWidForWeblogs::class,
];
然后使用那个中间件
所以对于你的路线组
Route::prefix('admin/{w_id}')->middleware(['auth', 'pass_wid'])->as('weblog.')->group(function () {
Route::get('/dashboard', [HomePageController::class, 'index'])->name('dashboard');
Route::resource('/blogcategory', CategoryController::class);
});
请参阅有关 default values to Url
的文档
我有一个具有这种结构的路由组:
Route::prefix('admin/{w_id}')->middleware(['auth'])->as('weblog.')->group(function () {
Route::get('/dashboard', [HomePageController::class, 'index'])->name('dashboard');
Route::resource('/blogcategory', CategoryController::class);
});
在仪表板路线上,我在 url 中有 w_id,当我想将用户重定向到 blogcategory 路线(从任何地方)时,我应该在路线助手 [=29] 中手动传递 w_id =],我需要从当前 link.
全局设置一些东西例如当我使用这个方法时:
'route' => 'weblog.blogcategory.store'
我收到如下错误:
Missing required parameters for [Route: weblog.blogcategory.store]
我应该手动将 w_id 参数传递给所有路由助手,我需要从页面的当前 url 全局设置 w_id。 我正在为用户的博客开发完全独立的管理区域,并且所有 url.
中都存在博客 ID为了避免再次传递 w_id,您需要使用 URL::defaults()
,它会为您的参数创建一个默认值。
您可以使用中间件来传递默认值。
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultWidForWeblogs
{
public function handle($request, Closure $next)
{
URL::defaults(['w_id' => /* pass the default value here*/]);
return $next($request);
}
}
现在在app/Http/Kernel.php
中注册中间件class(查看更多说明here)
protected $routeMiddleware = [
...
'pass_wid' => \App\Http\Middleware\SetDefaultWidForWeblogs::class,
];
然后使用那个中间件 所以对于你的路线组
Route::prefix('admin/{w_id}')->middleware(['auth', 'pass_wid'])->as('weblog.')->group(function () {
Route::get('/dashboard', [HomePageController::class, 'index'])->name('dashboard');
Route::resource('/blogcategory', CategoryController::class);
});
请参阅有关 default values to Url
的文档