Search code examples
laraveleloquentlaravel-bladelaravel-controllerlaravel-models

Pluck and Implode Method in Laravel?


I have three classes Student, Session and student classes it has a relationship (Student with Enrollment, Session with Enrollment and student Class with enrollment), when I do echo it show the result [{"id":1,"school_id":1,"class_id":1,"student_id":1,"session_id":1,"created_at":null,"updated_at":null}] ,i have plucked value from student class

{{implode(',',$en->school()->get()->pluck('school_name')->toArray())}}

Note it is working


same from Session it is also working but when I plucked from student class and need class_name it not show an error but not the plucked value from studentclass here is the same type of query in blade.php

{{implode(',',$en->studentclass()->get()->pluck('class_name')->toArray())}}

here is the relationship one to many in StudentClass Controller

public function enrollments()
    {
        return $this->hasMany(Enrollement::class);
    }

Enrollement Class

public function studentclass()
    {
        return $this->belongsTo(StudentClass::class);
    }

how to pick the class_name value from table using this relationship. thanks


Solution

  • Firstly, note that you can use the implode method on the illuminate/collection method:

    {{ $en->school()->get()->pluck('school_name')->implode(', ') }}
    

    which can be further shortened to

    {{ $en->school->pluck('school_name')->implode(', ') }}
    

    The studentclass can be plucked like so

    {{ $en->studentclass->pluck('enrollments.class_name')->implode(', ') }}
    

    using dot syntax to access the class name.

    to prevent this from creating a n+1 issue and reduce the number of queries ran, you should lazy load the relationship:

    {{ $en->load('studentclass.enrollments')->studentclass->pluck('enrollments.class_name')->implode(', ') }}
    

    you could also load it in advance:

    $en = Enrollment::with('studentclass.enrollments')->where('id', $id)->first();