Error using Laravel

0

I'm working on a project with Laravel and this function gives me an error. What I want to get is the name of the trainer who gives the course.

<span class="title">{{ $course->owner->specialization->getName() }}</span>

The error that appears is the following:

  

Relationship method must return an object of type
  Illuminate \ Database \ Eloquent \ Relations \ Relation

And so the functions in the classes are defined:

Inside the Courses class

public function owner()
    {
        return $this->belongsTo('App\User', 'user_id', 'id')->getResults();
    }

Inside the User class

public function specialization()
    {
        if($this->isTrainer()) return $this->trainer();
        if($this->isCenter()) return $this->center();
        return null;
    }
private function trainer()
    {
        return $this->hasOne('App\Trainer');
    }   

Inside the Trainer class

public function getName()
    {
        $name = '';
        if(!empty($this->name)) {
            $name .= $this->name;
        }
        if(!empty($this->last_name)) {
            $name .= ' ' . $this->last_name;
        }
        if(!empty($this->second_name)) {
            $name .= ' ' . $this->second_name;
        }

        return $name;
    }
    
asked by Tonio 23.02.2017 в 14:22
source

2 answers

0

To solve your problem in the simplest way you should use the "accessors" of Laravel, to be able to access more semantically speaking:

In your trainer class, to get the name the accessor would be something like this:

public function getFullNameAttribute()
{
    // código de la función getName()
}

This way you can use it like this in the view:

{{ $course->owner->specialization->full_name }}

You can see more information in the documentation: link

Small point aside, and although I do not understand very well the logic of your application and I do not know the reason why you do it, you could improve the code or the way you do the process in the specialization() method, as well as the logic with which you generate the full name.

    
answered by 23.02.2017 в 15:54
0

I see that the function specialization() can return null values, so in the view if you call $course->owner->specialization->getName() you will give an error in those cases.

One option would be to verify in the view if the value is null:

@if (empty($course->owner->specialization))
     <span class="title">Sin nombre</span>
@else
     <span class="title">{{ $course->owner->specialization->getName() }}</span>
@endif
    
answered by 23.02.2017 в 15:57