You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何从控制器返回指定分组下的资源路由?

Laravel 控制器中返回资源路由的方法

你当前的路由配置通过分组前缀prayer和名称前缀prayer.,注册了time资源路由,对应PrayerTimeController。这条资源路由会自动生成多个带命名的路由(可通过php artisan route:list查看完整列表,比如prayer.time.index、prayer.time.show等),在控制器中可根据需求按以下方式返回:

1. 重定向到资源路由

使用redirect()->route()方法,传入对应的路由名称即可完成重定向:

  • 重定向到资源列表页(对应index动作):
return redirect()->route('prayer.time.index');
  • 重定向到单条资源详情页(对应show动作,需传入资源ID或模型实例):
// 传入ID
return redirect()->route('prayer.time.show', 1);
// 直接传入模型实例,Laravel会自动提取ID
return redirect()->route('prayer.time.show', $prayerTime);
  • 重定向到资源创建页(对应create动作):
return redirect()->route('prayer.time.create');

2. 返回视图并传递数据

在资源控制器的对应动作方法中,直接返回视图并绑定所需数据:

  • 列表页(index方法):
public function index()
{
    $prayerTimes = \App\Models\PrayerTime::all();
    return view('prayer.time.index', compact('prayerTimes'));
}
  • 详情页(show方法,使用路由模型绑定):
public function show(\App\Models\PrayerTime $prayerTime)
{
    return view('prayer.time.show', compact('prayerTime'));
}

3. 返回JSON响应(API场景)

如果是开发API,直接返回模型或集合,Laravel会自动转换为JSON格式:

public function index()
{
    return \App\Models\PrayerTime::all();
}

public function show(\App\Models\PrayerTime $prayerTime)
{
    return $prayerTime;
}

内容的提问来源于stack exchange,提问作者abu abu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:10:28