Reputation: 2400
I am following a tutorial Articles and comments. Below works fine, but how do i get all comments with the articlename in a foreach?
Model: Article
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
public function comments() {
return $this->hasMany('App\Http\Models\Comment');
}
protected $fillable = array('title','body');
}
Model: Comments
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function article() {
return $this->belongs('Article');
}
protected $fillable = array('body','article_id');
}
Example dump in ArticleController:
$items = Article::find(1)->comments()->get();
foreach ($items as $item) {
print_r($item->body);
}
Upvotes: 0
Views: 794
Reputation: 2400
In the CommentController i dumped for example:
foreach ( $comments as $comment) {
echo $comment->body.' - '.$comment->article->title.'<br>';
}
Upvotes: 0
Reputation: 1529
From the documentation on querying relations
$article = Article::find(1);
echo $article->name;
foreach ($article->comments as $comment) {
//
}
Upvotes: 1