Wednesday, March 8, 2017

Laravel Eloquent add the withCount method

There are methods in controller which get all published posts sorted by published_at and show one post

public function show($id) {
        $post = Post::findOrFail($id);
        session()->reflash();
        return view('posts.show', compact('post', 'random'));
    }

public function index() {
        $posts = Post::latest('published_at')->published()->paginate(10);
        return view('home.index', compact('posts'));
    }

also every post has likes, so I need to get posts with likes and post with likes.
So I need to use something like that (That is example from documentation https://laravel.com/docs/5.2/eloquent-relationships#querying-relations)

$posts = App\Post::withCount('likes')->get();

How could I add withCount() method to my methods?



via Heidel

Advertisement