我使用laravel制作了简单的CMS,当我尝试在单一类别页面中发布帖子时。使用我在类别模型中指定的 $ category-> posts()但由于某种原因它&# 39;未定义,我得到以下错误
这是我的代码
类别模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function posts()
{
return $this->belongsToMany('App\Posts')->withTimestamps();
}
}
发布模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
public function user()
{
return $this->belongsTo('App\User');
}
public function meta()
{
return $this->hasMany('App\Postmeta');
}
}
**Category Controller**
<?php
namespace App\Http\Controllers\Frontend;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;
class CategoriesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function getIndex()
{
return view('frontend.categories.index')->withCategories(Category::orderBy('id', 'desc')->paginate(6));
}
/**
* Display the specified resource.
*
* @param int $slug
* @return \Illuminate\Http\Response
*/
public function getSingle($slug)
{
$category = Category::where('slug', '=', $slug)->first();
$posts = ($category !== null) ? $category->posts() : array();
return view('frontend.categories.single')->withCategory($category)->withPosts($posts);
}
}
答案 0 :(得分:1)
我认为你打错了。
您放置Posts
而不是Post
。
$this->belongsToMany('App\Post')
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
}