Good time, Thank you if they help me with this problem. I actually have this problem in Laravel that I'm new to Livewire.
Controller
class ViewCourse extends Component{
public $course;
public function mount($id , $name = null , $mediaID = null){
$this->course = course::findOrfail($id);
}
public function render(){
return view('livewire.view-course')->extends('layouts.app');
}
Relationship Models
class course extends Model{
public function teacher(){
return $this->hasOne('App\Models\User' , 'id' , 'user_id')->select('name' , 'picture');
}
}
Blade Code
<p>{{$course->teacher->name}}</p>
My Error
ErrorException
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\kjjk\resources\views\livewire\view-course.blade.php)
The problem is that you are not selecting the columns that Laravel needs to properly resolve the relationship and fetch the user model.
You can either remove the select or add the id
column to your select:
Removing the select:
public function teacher()
{
return $this->hasOne('App\Models\User', 'id', 'user_id');
}
Add required columns to the select:
public function teacher()
{
return $this->hasOne('App\Models\User', 'id', 'user_id')
->select([
'id',
'name',
'picture',
]);
}
I would personally just remove the select as I don't see any value in only selecting a few columns from the relationship. Additionally it will probably cause more headaches later down the line if you add more columns to the user table.