0

I'm trying to get name of a user using the following code, but i'm getting an error. please help. The error is

"Trying to get property 'name' of non-object (View: /var/www/html/laravel/imarker/resources/views/student/exams/available.blade.php)"

@foreach($availableExams as $exam)
     @foreach($exam->user as $user)
           {{($user->name)}}
     @endforeach
    @endforeach

Exam Model

 public function user(){
    return $this->belongsTo('App\User');
}

User Model

public function exams(){
    return $this->hasMany('App\Exam');
}

Controller

public function availableExams(){
    $users = User::all();
    $availableExams = Exam::all();
    return 
view('student/exams/available',compact('availableExams', 'users'));
   }
3
  • when i dd($user) it returns true instead of the name. what could be the name? Commented Apr 6, 2019 at 6:21
  • yes, because user method has relationship belongs to so it returns only one record, try to dd $exam->user in view you will get an idea. Commented Apr 6, 2019 at 6:30
  • why use two foreach?If each exam belongsTo one user you need one foreach in view..{{$exam->user->name }} Commented Apr 6, 2019 at 6:32

3 Answers 3

1

Each Exam has one User and that User has a name? Try this:

@foreach($availableExams as $exam)
    {{$exam->user->name }}
@endforeach
Sign up to request clarification or add additional context in comments.

5 Comments

this is crazy. when i {{dd($exam->user->name) }} i get the name, but once i use {{$exam->user->name}} i get the same error Trying to get property 'name' of non-object (View: ...
@TimothyMach when you use dd($exam->user->name) what's dump exactly?copy please
@mohammadHosseini I get "Mach Turor" - which is what I want.
Something is funky. Can you try {{ $exam->user()->first()->name }}
@Anders the problem was checking if a user exists. ` {{$exam->user->name ?? 'No tutor found'}} ` Thats how i solved it. Thanks so much. you gave me a hint
0

Got it. One user was missing. using an if statement to check if the object exists solves it. Using 2 arrows risks finding an empty item/object and that causes problems, hence the need for the condition clause. Thank you guys.

@foreach($availableExams as $exam)
    {{$exam->user->name ?? 'No tutor found'}} 
 @endforeach

Comments

0

Update your blade file.

@foreach($availableExams as $exam)
           {{ $exam->user()->first()->name }}
@endforeach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.