2 weeks ago

How to share the same data between methods in the controller?

Posted 2 weeks ago by 4unkur
    public function create()
        $categories = Category::with('subCategories')->get();

        return view('product.create')->with(compact('categories'));

    public function edit(Product $product)
        $categories = Category::with('subCategories')->get();

        return view('product.edit')
            ->with(compact('product', 'categories'));

Here's the controller and as you can see I share the same data between 2 methods. It's a simplified example, in reality there might me a lot more data. How can I make this code DRY? I know about View compose, but it seems not quite applicable for this situation and not that obvious. Maybe there are other ways?

Please sign in or create an account to participate in this conversation.