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

如何在Laravel网页中获取JSON格式的课程学生数据?

解决办法

方案1:根据请求头返回对应响应

利用Laravel的Request实例判断请求的Accept头,区分浏览器(HTML)和API客户端(JSON)请求:

修改控制器的show方法:

use Illuminate\Http\Request;

public function show(Request $request, Course $course)
{
    $students = $course->students()->get();

    // 判断是否需要返回JSON
    if ($request->wantsJson() || $request->ajax()) {
        return response()->json($students, 200);
    }

    // 否则返回视图
    return view('Course.show', compact('students', 'course'));
}
  • $request->wantsJson()可识别请求是否期望JSON响应(比如Postman设置Accept: application/json)
  • $request->ajax()兼容AJAX请求场景

方案2:新增独立的API路由

在api.php中新增专门的API路由,和原web路由分开:

// api.php
Route::get('courses/{course}/students', [CourseController::class, 'getStudents']);

然后在控制器中新增对应方法:

public function getStudents(Course $course)
{
    $students = $course->students()->get();
    return response()->json($students, 200);
}

原web.php的资源路由保持不变,继续返回视图。此时:

  • 浏览器访问/courses/25返回HTML视图
  • Postman访问/api/courses/25/students返回JSON数据

方案3:通过URL参数区分

在原路由基础上,通过URL参数format=json控制返回类型:
修改控制器方法:

public function show(Course $course)
{
    $students = $course->students()->get();

    if (request()->query('format') === 'json') {
        return response()->json($students, 200);
    }

    return view('Course.show', compact('students', 'course'));
}

使用方式:

  • 浏览器访问/courses/25返回视图
  • Postman访问/courses/25?format=json返回JSON

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:35:06