I have a weird issue with Models and their eloquent relations. The thing is that I have 2 Models , User and Subject. They are linked through belongsToMany relation like so :
class User extends Model {
public function allowed_subjects()
{
return $this->belongsToMany(Subject::class);
}
}
and
class Subject extends Model {
public function users()
{
return $this->belongsToMany(User::class);
}
}
the pivot table is named to convention "subject_user" and has "user_id" and "subject_id" fields. I defined a function in User class to check if the user has a certain subject like so :
public function hasSubject($subject='') {
$match = false;
if(is_string($subject)){
if(!empty($this->allowed_subjects)
{
return $this->allowed_subjects->contains('name',$subject)? true : false;
}
return false;
}
elseif(is_integer($subject))
{
if(!empty($this->allowed_subjects)
{
return $this->allowed_subjects->contains('id',$subject)? true : false;
}
return false;
}
elseif(is_array($subject))
{
foreach($subject as $sbj)
{
if(is_integer($sbj))
{
$this->allowed_subjects->contains('id',$sbj)? $match = true : null;
}
elseif(is_string($sbj))
{
$this->allowed_subjects->contains('name',$sbj)? $match = true : null;
}
else{
continue;
}
}
}
return $match;
}
The function is working fine locally , but once I hosted the app in a DO server , It acts so weird , that hasSubject always returns false even if the user has the subject . So I run its tests and they return all green . I defined a route to test this function live like so :
Route::get('/hasSubject', function(){
$cuser = \Auth::user();
//foreach($cuser->allowed_subjects as $sbj){
//echo $sbj->id." ".$sbj->name."<br>";
//}
echo "<hr>";
dd($cuser->hasSubject(1));
});
and then the magic happens , if I uncomment the foreach loop , it returns true (which is correct), but when it's commented , it return false and this is the case in all my controllers , if I print allowed_subjects before calling hasSubject it works fine , otherwise no . I am really losing my mind
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire