I have this code in my model called Tag:
<?php namespace App; use IlluminateDatabaseEloquentModel; class Tag extends Model { protected $fillable = [ 'tag' ]; public function articles(){ return $this->belongsToMany(Article::class); } }
and I use this code in my controller
public function fillter($target){ $tags = tag::where('id', 3)->count(); $article = $tags->articles; foreach ($article as $article){ return $article->title; } }
when I run the code, I get an exception: Property [articles] does not exist on this collection instance.
but if I am able to run the following code:
$tags = tag::where('id', 3)->first();
Advertisement
Answer
You are practically trying to get articles from integer value, since that is what count()
function returns. This line of code returns an integer:
$tags = tag::where('id', 3)->count(); // For ex: 3
And you are trying to do this in the next line of code:
$article = 3->articles; //Which doesn't exist
By using this line of code here:
$tags = tag::where('id', 3)->first();
You are returning a Tag
instance, which in fact has the articles
property.
Also, your foreach
code won’t work because of two reasons:
First: You can’t use same variable in your foreach loop, it should be like this:
foreach($articles as $article)
Second: It will stop executing after the first loop, since you have a return statement:
foreach ($articles as $article){ return $article->title; }
It would be better to pass the $articles
variable to your view, and do a foreach loop there.