public function language() {
return $this->belongsTo('Language','lang_id');
}
Laravel - Trying to get property of non-object
-
16-07-2023 - |
문제
I'm puzzled with this: I'm trying to build some multilingual support in some kind of a blog format. I have some posts (that i call news) that i need in two languages. What I have right now is a languages table and a newss table.
languages - id - name - code
newss - id - parent_id - lang_id - slug - title - body
Everything is working fine until now. I'm able to save news to the database. The only annoying problem is that in the index news page i'm unable to get the languages codes. I have a foreach loop with {{ $news->language->code}} that retrieves "Trying to get property of non-object".
I'll share my models, controllers and views with you in hope some one can bring some light on the mistakes i'm over seeing.
Models:
Languages.php
<?php
class Language extends Eloquent {
protected $fillable = array('name', 'code');
public static $rules = array(
'name'=>'required|min:3',
'code'=>'required|min:2'
);
public function news() {
return $this->hasMany('News');
}
}
News.php
<?php
class News extends Eloquent {
protected $fillable = array('parent_id', 'lang_id', 'slug', 'title', 'body');
protected $table = 'newss';
public static $rules = array(
'parent_id'=>'integer',
'lang_id'=>'required|integer',
'title'=>'required|min:3'
);
public function language() {
return $this->belongsTo('Language');
}
public function parent_news() {
return $this->belongsTo('News','parent_id');
}
public function child_news() {
return $this->hasMany('News','parent_id');
}
}
Controller:
NewsController.php
public function index()
{
$newss = News::all();
$languages = array();
foreach(Language::all() as $language) {
$languages[$language->id] = $language->code;
}
return View::make('admin.news.index')
->with('newss', $newss)
->with('languages', $languages);
}
View:
@foreach($newss as $news)
<tr class="gradeA">
<td>{{ $news->title}}</td>
<td>{{ $news->language->code}}</td>
<td>{{ HTML::linkRoute('admin.news.edit', '', array($news->id), array('class' => 'btn btn-warning btn-circle glyphicon glyphicon-pencil')) }}</td>
<td>{{ Form::open(['method' =>'DELETE', 'route'=>['admin.news.destroy', $news->id], 'class'=>'form-inline']) }}
{{ Form::hidden('id', $news->id) }}
{{ Form::button('<i class="fa fa-times"></i>', array('type' => 'submit', 'class' => 'btn btn-danger btn-circle')) }}
</td>
{{ Form::close() }}
</tr>
@endforeach
해결책