试图获得非对象的属性[laravel 5.2]

project VERSION 5.2

I am a new Laravel 5 learner. plz solve ...

error:Trying to get property of non-object

Comment.php [model]

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    //
    public function articals()
    {
        return $this->belongsTo('App\Artical');
    }

    protected $fillable = array('body','artical_id');


}

Article.php [model]

namespace App;

use Illuminate\Database\Eloquent\Model;

class Artical extends Model
{
    //
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }

    protected $fillable = array('title','body');


}

route.php [route]

 use App\Artical;
 use App\Comment;

Route::get('/', function ()
{

 $c = Artical::find(18)->comments;
  foreach($c as $comment) 
  {
    print_r($comment->body.'<br />'); 
  }
}); // working ok.....but

  $a = Comment::find(18)->articals;
  print_r($a->title); // error:Trying to get property of non-object 




}

getting error:Trying to get property of non-object

plz help me...

article table structure

comment table structure

I think your relationships might be off. Guessing from the code the relationship is Many to many? If so, then those relationships should be belongsToMany. Also make sure you're defining the relationship and it's inverse on the right models (depending on which has the foreign key).

https://laravel.com/docs/5.2/eloquent-relationships#defining-relationships

The problem is your articles() relationship on your Comment model.

When you don't specify the foreign key on the belongsTo relationship, it builds the foreign key name based on the name of the relationship method. In this case, since your relationship method is articles(), it will look for the field articles_id.

You either need to rename your articles() relationship to article() (which makes sense, since there will only be one article), or you need to specify the key name in the relationship definition.

class Comment extends Model
{
    // change the relationship name
    public function article()
    {
        return $this->belongsTo('App\Article');
    }

    // or, specify the key name
    public function articles()
    {
        return $this->belongsTo('App\Article', 'article_id');
    }
}

Note, this is different than the hasOne/hasMany side of the relationship. It builds the key name based on the name of the class, so there is no need to change how your comments() relationship is defined on the Article model.

Change following line

$a = Comment::find(18)->articles;

to

$a = Comment::find(18);