skip to Main Content

my model

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

my controller code

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

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

2

Answers


  1. Chosen as BEST ANSWER

    the another way:

     $semesters = Auth::guard('student')->user()->semesters;
     return view('dashboards.student.home',['semester'=>$semesters[0]['name']]);
    

    **this is very simpale i also get idea from another stackovreflow question and also working for me **


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search