Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get first record in many to many relationship using laravel

my model

 public function semesters(): BelongsToMany
    {
        return $this->belongsToMany(Semester::class)
        ->orderBy('name', 'desc');
    }

my controller code

$semesters = Auth::guard('student')->user()->semesters;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my blade code is

{{ dd($semesters->name) }}

and the error is

Property [name] does not exist on this collection instance.

my expectation is to get singal semester name in blade

>Solution :

The error you’re facing is due to the issue you’re not referring to the correct data. You can do it by doing something like this:

$semesters = Auth::guard('student')->user()->semesters;
$semesterName = $semesters->first()->name;
return view('your-blade-view', compact('semesterName'));

and then you can use semesterName to render the name on frontend. The code will fetch the first result and then get the name from the result. Hope this helps.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading