R
R
RobQwerty2021-02-21 13:22:08
Laravel
RobQwerty, 2021-02-21 13:22:08

What is the correct way to get data in a controller function?

Greetings, please tell me how to get the data correctly
In the controller, all models are connected, everything is connected.
There is a posts table, it has a column with category id. How can I implement a process to get the name of this category on the fly with category_id. And how can I optimize this process? I post the code below. Thank you!

public function posts(){
        $posts = Post::select('id','category_id','title', 'slug', 'created_at')->whereType('post')->orderBy('id', 'desc')->paginate(20);
        $categories = NewsCategory::select('category_name')->whereId($posts->category_id)->get();
        return view('admin.news.posts', compact('title', 'posts'));
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
ninja op op, 2021-02-21
@RobQwerty

$posts = Post::where('type', 'post')->join('news_categories', 'posts.category_id', '=', 'news_category.id')->select('posts.id','posts.category_id','posts.title','posts.slug','posts.created_at','news_categories.category_name')->orderBy('posts.id', 'desc')->paginate(20);

return view('admin.news.posts', compact('posts'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question