I have a very, very strange problem.
What I try to do is to create tags on my blog posts. Therefor I use a ManyToMany relationship.
This is a fresh installed Laravel 5.1:
routes.php
Route::get('/{id}', 'BlogController@show');
Models
Blog.php
class Blog extends Model
{
public $timestamps = false;
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Tag.php
class Tag extends Model
{
public function blogs()
{
return $this->belongsToMany('App\Blog');
}
}
Controller
BlogController.php
class BlogController extends Controller
{
public function show($id)
{
$blog = Blog::find($id);
return view('welcome', compact('blog'));
}
}
Welcome.blade.php
<h1>{{ $blog->title }}</h1>
<h2>Tags</h2>
@foreach($blog->tags as $tag)
<p>{{$tag->name}}</p>
@endforeach
All the required tables are created (blogs, tags, blog_tag) and some posts and tags are created and relations are set (attach) in blog_tag.
When I run this I get this error
Invalid argument supplied for foreach() (View: /var/www/http://ift.tt/21flEjw)
It seems that is has something to do with $blog->tags. If I change it to $blog->tagss and also change the method name in Blog.php to tagss ( public function tagss() ) it is working flawlessly...
I don't get it. I know I can simply change it to tagss or something else but I am following simple tutorials here, so this should work?
Is 'tags' a reserved word or is there something else I don't see? Again, this is a fresh Laravel Installation. What am I missing here?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire