Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Hi This is my controller of an application im makeing in laravel 9 and it runs 3 times the same sql te 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
        ]);
    }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading