Use query scopes.
Jan 21, 2021
4
Level 12
Custom filtering data
If all I have is this:
public function searchByCategory(Post $post, Category $category)
{
$post = Post::where('category_id', $category->id)
->latest('id')
->paginate(8);
$category = Category::get();
return view('posts.category', ['posts' => $post, 'category' => $category]);
}
And im using it to see all posts regarding a category, would it be wise to create a controller just for this? I was using it inside my PostsController but I don't want it to be mixed with the CRUD essentials.. This works though, I don't think it's the most advanced thing ever and I dont neccesarily need it but im mainly looking for suggestions :-)
I mean, when I say it's not the most advanced thing ever is because you look at the data through an <a href=""> anchor tag element:
<span> Category: </span>
<a href="{{ route('posts.category', $post->category) }}">
{{ $post->category->name }}
</a>
Level 75
In docs: https://laravel.com/docs/8.x/eloquent#query-scopes
But probably a video also. One is https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/21
But you can search for others.
1 like
Please or to participate in this conversation.