PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

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

 April 19, 2022     laravel, laravel-9, php     No comments   

Issue

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



Answered By - Sergei
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing