Reputation: 2329
I made simple CMS using laravel and when i try to get posts inside single category page.Using $category->posts() which i assigned in my category model but for some reason it's not defined and i get the following error
And here is my codes
Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function posts()
{
return $this->belongsToMany('App\Posts')->withTimestamps();
}
}
Post Model
<?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);
}
}
Upvotes: 0
Views: 51
Reputation: 2919
I think you made a typo.
You put Posts
instead of 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();
}
}
Upvotes: 1