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