我使用Laravel并收到此错误:
尝试获取非对象的属性(查看:C:\ laragon \ www \ al-Zad \ resources \ views \ blog \ index.blade.php)
问题出在这一行:
<li><i class="fa fa-user"></i><a href="#"> {{$post->author->name}} </a></li>
这些是模型:
发布模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class post extends Model
{
public function author()
{
return $this->belongsTo(User::class);
}
}
用户模型:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany(post::class);
}
}
我该如何解决问题?
答案 0 :(得分:-1)
在你的帖子模型中你应该添加这个功能:
public function author(){
return $this->hasOne('App\User');
}
在视图中你应该把它放在:
{{$post->author()->name}}