I have been trying to matching the data from database in a Laravel project but always gave me an alert: Undefined offset: 0 . I have checked different posts in this website but many situations could arise this alert.
The strange point is that if I don't perform matching process, the program works fine but vice versa. Just not sure what's wrong with my code.
This is the controller.
public function addProductAction(Request $request) {
/*
check if any input is empty, if validation is fail, error message will display.
Get required information from addProduct view. And then pass then in the $sql variables.
DB class will map then to get result.
*/
$this->validate($request,[
"product_name" => "required | max:20",
"description" => "required | max:255",
"date_of_release" => "required",
"id" => "required"
]);
$product_name = request("product_name");
// dd($product_name);
$description = request("description");
$manufacturer_id = request("id");
$date_of_release = request("date_of_release");
$sql = "SELECT product_name FROM PRODUCT where product_name = ?";
$existingProducts = DB::select($sql, array($product_name));
$existingProduct = $existingProducts[0] -> product_name;
//dd($existingProduct);
if ($product_name == $existingProduct) {
echo "product exists";
} else {
$sql = "insert into product (product_name, description, date_of_release) values (?, ?, ?)";
DB::insert($sql, array($product_name, $description, $date_of_release));
$id = DB::getPdo()->lastInsertId();
//dd($id);
$sql = "insert into PRODUCT_ORIGINAL (product_id, manufacturer_id ) values (?, ?)";
DB::insert($sql, array($id, $manufacturer_id));
// dd($newProduct);
return redirect("product-detail/$id");
}
return redirect('/');
}
This is error message:
at HandleExceptions->handleError(8, 'Undefined offset: 0', '/home/ubuntu/workspace/project_product/app/Http/Controllers/ProductController.php', 216, array('request' => object(Request), 'product_name' => 'Apple iPhone 10', 'description' => 'It is a good computer', 'manufacturer_id' => '1', 'date_of_release' => '2018-09-01', 'sql' => 'SELECT product_name FROM PRODUCT where product_name = ?', 'existingProducts' => array()))
in ProductController.php line 216