Axios returns 500 error status code when data exists
P粉275883973
P粉275883973 2023-08-30 17:42:42
0
1
520
<p>I am using <code>Laravel 8</code>, <code>VueJS</code> and <code>Axios</code> to develop my application but every time I try to retrieve data from database When fetching all the records in it, it returns an error with status code 500. Even though there are no errors when using Postman/Insomnia to get the data. </p> <p>I tried clearing the table from which the data was obtained, the error disappeared and empty data with status code 200 was returned. </p> <p><strong>Store module: </strong></p> <pre class="brush:php;toolbar:false;">import axios from 'axios' export default { namespaced: true, state: { courses: [], teacher: '', }, getters: { allCourses(state) { return state.courses }, }, actions: { async fetchAllCourses({ commit }) { const response = await axios.get('teacher/course-management/list') console.log(response.data.data) commit('SET_COURSES', response.data.data) } }, mutations: { SET_COURSES(state, courses) { state.courses = courses } }</pre> <p><strong>Controller: </strong></p> <pre class="brush:php;toolbar:false;">public function fetchAllCourses() { try { $courses = Course::all()->sortBy('id'); $data = $courses->transform(function ($course) { // ! Get teacher ID $teacherId = $this->user->teacher->id; // ! Get the teacher's name based on ID $teacherName = $this->getTeacherName($teacherId); return [ 'id' => $course->id, 'teacher_id' => $course->teacher_id, 'teacher' => $teacherName, 'section' => $course->section, 'code' => $course->code, 'status' => $course->status, 'image' => $course->image, ]; }); return $this->success('Request successful', $data); } catch (\Exception $e) { return $this->error($e->getMessage(), $e->getCode()); } }</pre></p>
P粉275883973
P粉275883973

reply all(1)
P粉486743671

problem solved.

public function fetchAllCourses() {
        try {
            $courses = Course::all()->sortBy('id');
    
            $data = $courses->transform(function ($course) {
                return [
                    'id' => $course->id,
                    'teacher_id' => $course->teacher_id,
                    'teacher' => $this->getTeacherName($course->teacher_id),
                    'section' => $course->section,
                    'code' => $course->code,
                    'status' => $course->status,
                    'image' => $course->image,
                ];
            });
    
            return $this->success('请求成功', $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }   
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template