Laravel 5.1 - Relations method must return an object of type

My application accepts payments from users, but subtitles are not allowed to view the payment screen.

I have a Route::group that checks if the user is allowed to pay through Middleware. The handle function looks like this:

  if(!\Auth::user()->isTeacher) { \Auth::logout(); return redirect('/login')->withErrors([$error = 'Sorry there was a problem. Please notify your School']); } return $next($request); 

and isTeacher() function

 if($this->school_id) { $teachers = $this->school->find($this->id)->teachers; $isTeacher = false; foreach ($teachers as $teacher) { if ($teacher->id == \Auth::user()->id) {$teacher = true;} } return $isTeacher; 

}

Finally, the school’s relationship is as follows

 return $this->hasOne('App\School', 'id', 'school_id'); 

The error I am getting is

LogicException in Model.php line 2667: Relations method should return an object of type Illuminate \ Database \ Eloquent \ Relations \ Relation

In the part of the error tree? it shows that this is from middleware

in Model β†’ __ get ('isTeacher') in the line MustBeTeacherToMakePayment.php 19

which is the if statement in the first line above.

Can anyone tell me what I'm doing wrong? It drives me crazy.

+4
source share
1 answer

Instead of calling the isTeacher () function, you get access to the isTeacher attribute. Eloquent sees the method of this name and identifies it as the method that should return the definition of the relationship. And then you get an error, because relationship determination methods must return a Relation object.

You must replace

 if(!\Auth::user()->isTeacher) 

from

 if(!\Auth::user()->isTeacher()) 

and the error will disappear.

+9
source

All Articles