gpt4 book ai didi

php - 拉维尔 5.7 : Cleanest way to generate nested urls in views

转载 作者:搜寻专家 更新时间:2023-10-31 21:20:02 24 4
gpt4 key购买 nike

我目前有嵌套路线。

假设我有

Route::resource('a', 'AController');
Route::resource('a.b', 'BController');
Route::resource('a.b.c', 'CController');

在我看来,是否有比以下方法更好的生成 URL 的方法:

route('a.b.c.show', ['a'=>$aId, 'b'=>$bId, 'c'=>$cId])

嵌套 URL 有点烦人。为什么我们不能只传递一个 Eloquent 模型实例?像 route('a.b.c.show', $cInstance)

谢谢

最佳答案

我经常将生成 url 的责任传递给模型,例如 setter/getter :

$cInstance->url
public function getUrlAttribute() {
return route('a.b.c.show', $this);
// or:
// return action([CController::class, 'show'], ['a' => $this]);
}

但这取决于您的用例。普通方法同样有效,比如如果你想添加比模型已知的更多的参数。例如:

public function url($b, $c) {
return route('a.b.c', ['a' => $this, 'b' => $b, 'c' => $c]);
}

但是,如果您只是在谈论在使用模型之前从模型中获取 ID,就像在这种情况下:

$aId = $a->id;
return route('a', ['a' => $aId]);

然后 Laravel 实际上确实已经支持了:route('a.b.c.show', compact('a', 'b', 'c')) 应该可以正常工作. Eloquent 模型实现了 Illuminate\Contracts\Routing\UrlRoutable 接口(interface),它有一个 getRouteKey() 方法,路由器知道如何使用。

关于php - 拉维尔 5.7 : Cleanest way to generate nested urls in views,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com