Getting data from another table into a blade foreach
I have two tables: Articles and Author. The Article table has a foreign key called author_id which relates to the Authors id. I have set relationships: Author has many Articles and the Articles belong to a Author. How would I get the Authors name in a blade foreach even though it is in a different table ?
Assuming your relationship method in the Article model is names "author" you would just add ->with('author') to the query you are running to pull the articles.
I added the above to my controller and now I see an error saying "Fatal error: Class 'User' not found". All of my namespaces are correct.
These are my model:
Article:
<?php
namespace Politicentral;
use Politicentral\User;
use Illuminate\Database\Eloquent\Model;
class Articles extends Model {
protected $fillable = [
'title',
'body',
'article_image',
];
public function User() {
return $this->belongsTo('User');
}
}
Author/User
<?php
namespace Politicentral;
use Politicentral\Articles;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable {
protected $table = 'authors';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function Article() {
return $this->hasMany('Articles');
}
public function fullName() {
return $this->first_name . ' ' . $this->last_name;
}
}
You would access it using $article->User->fieldname
I would rename the relationship to something more useful than User like author.
Another note the relationship should have the fully qualified classname to the model.
public function author() {
return $this->belongsTo('Politicentral\User');
}
The same should be true of the relationship from the other side. It should look something like.
public function articles() {
return $this->hasMany('Politicentral\Articles');
}
I though it work but it hasn't! I am now getting this error "Trying to get property of non-object" when I do this in my blade view "{{ $article->User->fieldname }}"