Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 5.2在从数据库获取数据时尝试获取非对象的属性_Laravel_Orm_Laravel 5.2_Blade - Fatal编程技术网

Laravel 5.2在从数据库获取数据时尝试获取非对象的属性

Laravel 5.2在从数据库获取数据时尝试获取非对象的属性,laravel,orm,laravel-5.2,blade,Laravel,Orm,Laravel 5.2,Blade,我在使用laravel 5.2我有两个模型 教授: class Prof extends Model { protected $fillable=array('nom','prenom','age','mail'); public function matieres(){ return $this->hasMany(Matiere::class,'id_prof'); } } 马蒂埃: class Matiere extends Model { protec

我在使用laravel 5.2我有两个模型

教授:

  class Prof extends Model
{
  protected $fillable=array('nom','prenom','age','mail');

public function matieres(){

    return $this->hasMany(Matiere::class,'id_prof');
}
}
马蒂埃:

class Matiere extends Model
{

    protected $fillable=array('Nom');

public function profs(){
        return $this->BelongsTo(Prof::class,'id_prof');
    }
}
在MatierController中,我有一种方法可以提供所有Matiere:

public function index()
    {
        $matiere = Matiere::all();
        return view('Matiere.index',compact('matiere'));
    }
在我看来,我显示了我的Matiere列表以及教授这门学科的教授的姓名(Matiere)

但是我得到了这个错误

尝试获取非对象的属性


我怎样才能解决这个问题?thnks

首先,您不需要在hasMany和BelongsTo中指定外键,这有点神奇,但通常雄辩的是,您能够理解并从外键中搜索正确的id(如果您在迁移文件中创建了外键关系)

其次,当您在blade代码中执行foreach时,调用
$mat->profs
,如果我没有弄错,它将返回一个集合或数组,而不是返回一个对象数组。这就是为什么在尝试获取非对象的属性时会出现错误

因此,要解决这个问题,您需要执行以下操作

@foreach ($matiere as $mat)
    @foreach ($mat->profs() as $pr)
        {{$pr->prenom}}
    @endforeach                
@endforeach
如果在
$mat
对象上调用方法
profs()
,则它将返回一个对象数组


Bonne chance pour la suite;)

我只使用一个foreach来修复它

@foreach ($matiere as $mat)
      {{ $mat->profs->prenom}}               
@endforeach

太感谢你了:)
@foreach ($matiere as $mat)
      {{ $mat->profs->prenom}}               
@endforeach