Search code examples
phplaravellaravel-9

How can I optimize my controller so it runs 1 query instead of 3


Below is the controller of an application I am making in Laravel 9. It runs the same SQL 3 times to get the id. Is there a way to optimize it, so it just runs once?

class ProductController extends Controller
{
    public function index()
    {
        return view('products.index', [
            'products' => product::paginate(6)->withQueryString()
        ]);
    }

    public function show($id, $name = null)
    {
        // Checks if product exists
        if (!product::find($id)) {
            return dd('Product not found');
        }

        $slug = Str::of(product::find($id)->name)->slug('-');

        //Checks if product name is set
        if (!$name || $name != $slug) {
            return redirect()->route('products.show', [
                'id' => $id,
                'name' => $slug
            ]);
        }

        //if all above is coorect then return view
        return view('products.show', [
            'product' => product::find($id)
        ]);
    }
}

Solution

  • Simply use variable $product.

    class ProductController extends Controller {
    
        public function index() {
            return view('products.index', [
                'products' => product::paginate(6)->withQueryString()
            ]);
        }
    
        public function show($id, $name = null) {
    
            $product = product::find($id);
    
            //Checks if product exists
            if (!$product) {
                return dd('Product not found');
            }
    
            $slug = Str::of($product->name)->slug('-');
    
            //Checks if product name is set
            if (!$name || $name != $slug) {
                return redirect()->route('products.show', [
                    'id' => $id,
                    'name' => $slug
                ]);
            }
    
            //if all above is coorect then return view
            return view('products.show', [
                'product' => $product
            ]);
        }
    }