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

Time:04-04

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

CodePudding user response:

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

CodePudding user response:

variable variable variable!

A variable in PHP is a name of memory location that holds data. In PHP, a variable is declared using $ sign followed by variable name. The main way to store information in the middle of a PHP program is by using a variable.

so a variable can stand for a value in all over of your code block! try to define a variable for your query, then try to call it wherever your code need to use it:

$product_query = product::find($id);

CodePudding user response:

In your public function show($id, $name = null) fetch the value of id into a variable first: $productById = $product::find($id);

Subsequently in the function use $productById everywhere instead of $product::find($id).

(I just described what @lagbox commented in a more elaborated way.)

  • Related