0

Basically, I have the following table structure for subject and Levels, Although few levels can have the parent of id 1 and few categories can have the other parent id. please see the following example

In this case Pre School, Primary, Intermediate are the levels of the Academmics Category

Subject Categories & Levels

--------------------------------------------------
| Id | Name        | Parent_id       |
--------------------------------------------------
| 1 | Academic     | NULL            |
--------------------------------------------------
| 2 | Arts         | NULL            |
--------------------------------------------------
| 3 | Languages    | NULL            |
--------------------------------------------------
| 4 | Pre School   | 1               |
--------------------------------------------------
| 5 | Primary      | 1               |
--------------------------------------------------
| 6 | Intermediate | 1               |
--------------------------------------------------

Other than that, I have a subjects table, which is relevant to the academics category, please see the following example

Subjects

--------------------------------------------------
| Id | Name       | slug       |
--------------------------------------------------
| 1 | Drawing     | drawing    |
--------------------------------------------------
| 2 | English     | english    |
--------------------------------------------------
| 3 | Maths       | maths      |
--------------------------------------------------

Subject category relations

--------------------------------------------------
| Id | subject_id   | subject_category_id       
--------------------------------------------------
| 1 | 1             | 4       
--------------------------------------------------
| 2 | 2             | 5      
--------------------------------------------------
| 3 | 3             | 6      
--------------------------------------------------

I am getting the following error when I am trying to get list of all the subjects with selected, please check the screenshot

Note: Its listing fine on load, but Its giving me the error on form submission and loading with selected subjects, Although record is saving in the database correctly.

exception: "ErrorException"
file: "/[project-directory]/vendor/laravel/framework/src/Illuminate/Support/Collection.php"
line: 1802
message: "Undefined offset: 0"

Please help me to fix this

Route:

Route::resource('/tutor/subjects', 'TutorSubjectAPIController')->except([
        'create', 'edit', 'show', 'update'
    ]);

Controller (API)

public function index(Request $request)
    {
        $user = $request->user();
        $tutorSubjects = $user->tutor->subjects;
        if(!$tutorSubjects->isEmpty()){
            $tutorSubjectsData['data'] = self::subjectsMapper($tutorSubjects);
            $findTutorParentCategory = DB::table('subject_tutor')->where([
                'tutor_id' => $user->tutor->id,
                'subject_id' => 0
            ])->get();
            $parentCategory =  $findTutorParentCategory['0']->subject_category_id;
            $tutorSubjectsData['parent_category_id'] = $parentCategory;

            return $this->sendResponse($tutorSubjectsData);
        }else{
            return $this->sendResponse('', 'No subjects found.',206);
        }
    }

Subject Mapper

public static function subjectsMapper($subjects){
        foreach ($subjects as $subject) {
            $data[] = [
                'subjectId' => $subject->pivot->subject_id,
                'categoryId' => $subject->pivot->subject_category_id,
            ];
        }
        return $data;
    }
Muhammad Owais
  • 980
  • 3
  • 17
  • 37
  • collection.php is meant the default collection.php of laravel... Its not written by me. ```/vendor/laravel/framework/src/Illuminate/Support/Collection.php``` – Muhammad Owais Apr 07 '19 at 18:57
  • Could you update your question with an example input and expected output for your function? – mdexp Apr 07 '19 at 19:16

1 Answers1

0

The problem is that you're using a collection as an array in your controller. In fact you are trying to access $findTutorParentCategory['0']->subject_category_id;, but $findTutorParentCategory is a collection returned by the query on the line above it.

If your query should only return one result, just replace ->get() with ->first() in the query.

To get the subject category id, you can get it directly from the findTutorParentCategory variable without using is as an array:

public function index(Request $request)
{
    // Rest of code..
        $findTutorParentCategory = DB::table('subject_tutor')->where([
            'tutor_id' => $user->tutor->id,
            'subject_id' => 0
        ])->first();
        $parentCategory =  $findTutorParentCategory->subject_category_id;
    // Rest of code..
}

Update: After some messages in chat, we got to the solution

public function index(Request $request)
{
    $tutor = $request->user()->tutor;
    $tutor->load('subjects.categories');

    if ($tutor->subjects->isEmpty()) {
        return $this->sendResponse('', 'No subjects found.', 206);
    }

    $subjects = $tutor->subjects->map(function ($subject) { 
        $category = $subject->pivot->subject_category_id;

        return [
            'subject_id ' => $subject->pivot->subject_id,
            'category_id ' => $category,
            'parent_category_id' => $subject->categories()->find($category)->parent_id
        ]; 
    });

    // dd($subjects); 
    return $this->sendResponse($subjects); 
}

To produce tuples with subject_id, category_id, subject_category_id for each subject related to a tutor.

mdexp
  • 3,492
  • 2
  • 9
  • 20
  • Its giving me this error ```Trying to get property 'subject_category_id' of non-object``` – Muhammad Owais Apr 07 '19 at 19:03
  • This means your query is returning null as no entry has been found in database with that `tutor_id` and `subject_id`. You could handle that case manually or use `->firstOrFail()` instead of `->first()`. That would generate a 404 if no query has matched your criteria. – mdexp Apr 07 '19 at 19:11
  • Its giving me ```Method Illuminate\\Database\\Query\\Builder::firstOrFail does not exist.``` – Muhammad Owais Apr 07 '19 at 19:28
  • My bad, I was thinking about Eloquent which has `->firstOrFail()` method. Query builder doesn't have it, so you have to use `->first()` and check manually if `$findTutorParentCategory` is null or not. – mdexp Apr 07 '19 at 19:31
  • ok, no worries, can you please give me the sample code? Thanks – Muhammad Owais Apr 07 '19 at 19:43
  • Could you first update the question with a sample input and expected output? Because from the code/explaination isn't that clear what you are trying to achieve with this piece of code. – mdexp Apr 07 '19 at 19:49
  • I have edited the question, please have a look and let me know if still have confusion – Muhammad Owais Apr 07 '19 at 20:24
  • Correct me if I'm mistaken: you are trying to get the main category (for instance: Academic) for all the subjects (eg: math) a tutor has been associated with? For each subject you want this tuple in output: `subject_id`, `category_id`, `parent_category_id`, am I right? – mdexp Apr 07 '19 at 20:57
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191414/discussion-between-mdexp-and-muhammad-owais). – mdexp Apr 07 '19 at 22:17