Please try this
$students = $course->students()->get();
$response = [ 'success' => true, 'students' => $students, ];
return response()->json($response, 200);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have done a web page using laravel. This web page is to store courses with sudents and some data. Now I`d like to get information as JSON but I don´t know how to do it.
Here´s my funtion show in my controller to show all the students stored in a course:
public function show(Course $course) { $students = $course->students()->get(); return view('Course.show',compact('students','course')); } The url that appears in my navigatio bar is: http://tfg.test/courses/25 because I´m doing it locally. Now, if I use Postman to make a get request to that url I receive the whole html page, but no JSON data. I don´t know how this is done.
I have tried doing this:
public function show(Course $course) {
$students = $course->students()->get();
return response()->json($students, 200);
/* return view('Course.show',compact('students','course')); */
}
And I get the JSON but I don`t go to the view in the web page
This is my route in web.php: Route::resource('courses', CourseController::class);
A friend told me to do this: public function show(Request $request,Course $course) { $students = $course->students()->get(); if($request->ajax()){ return response()->json($students, 200); }else{ return view('Course.show',compact('students','course')); } }
to get the view when using the navigator and get the JSION in other case but it doesn`t work because when I navigate I get the view and if I make a get request to that url via postman I get the view too and not the json.
Thank you.
Please or to participate in this conversation.