Home » Php » php – Laravel return resource collection to join table result

php – Laravel return resource collection to join table result

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m making a query with a join, because I need to search for all corrections of a student’s essays in specific. I know that my query returns correctly, because if I put it in the return I can get the json of the corrections.

However I want to return a data structure based on my correction JsonResource, and I’m trying to do it as follows:

public function studentindex (Student $student)
    {
        try {
            $result = DB::table('correction')
                -> join('essay', 'correction.essay_id', '=', 'essay.id')
                -> where('correction.deleted_at', '=', null)
                -> where(essay.student_id, '=', $student-> id)
                -> select('correction.*')
                -> get();
            
                if (empty ($result)) {
                    return response () -> json ("There are no corrections", 204);
                }

            return CorrectionResource::collection($result);
        } catch (\ Exception $ex) {
            dd ('Exception block', $ex);
            Log::error (print_r ($ex, true));
            dd ('Exception block', $ex);
            return response()->json ("It was not possible to set up the query, contact the administrator", 500);
        } catch (\ Throwable $ex) {
            dd ('Throwable block', $ex);
            Log::error (print_r ($ex, true));
            return response()->json ("It was not possible to set up the query, contact the administrator", 500);
        }
    }

What I also failed to do is get the error back, I don’t know if I have to put any imports, but nothing returns to me on the console, nor on the exit.

Can someone tell me if it is possible to do this “CorrectionResource::collection ($ result)” that I am trying?

How to&Answers: