2017-05-22 1 views
0

私はLaravelを使用していますが、 :Laravelエラー:非オブジェクトのプロパティを取得しようとしています(表示:C: laragon www al-Zad resources views blog index.blade.php)

Trying to get property of non-object (View: 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); 
    } 
} 

Userモデル:私は問題を解決するにはどうすればよい

<?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); 
    } 
} 

+1

をそのポストは、著者を持っていますか? – aynber

+1

投稿には著者がありません。またはあなたの関係は機能していません。 – devk

答えて

-1

あなたのポストモデルでは、この機能を追加する必要があります

public function author(){ 
    return $this->hasOne('App\User'); 
} 

を、ビューに、あなたは、この置く必要があります。

{{$post->author()->name}} 
+0

このエラーが発生しました: – mohammed

+0

未定義のプロパティ:\ Database \ Eloquent \ Relations \ BelongsTo :: $ name(ビュー:C:\ laragon \ www \ al-Zad \ resources \ views \ blog \ index.blade.php) – mohammed

+0

これは1つ以上の点で間違っています。関係は本当に意味をなさない。あなたが提案したやり方は、ユーザモデルに 'post_id'があると思います。モデル関係を次のような関数として呼び出すと、 '$ model-> relationship()'はモデルではなくクエリオブジェクトを返します。したがって、モハメドのエラーが発生しました。 – devk

関連する問題