Reputation: 427
I'm writing a search function in Laravel, and it throws the following error: QueryException in Connection.php line 651:
SQLSTATE[22018]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value '[]' to data type int. (SQL: select * from Product where pID = [])
.
My controller reads as follows:
public function productSearch(Request $request){
$searchResult;
if($request->input('category') == 'all' ){
$searchResult = Product::where("pCategory", "like", '%')
->where('pName', 'like', $request->input('search'))->get();
}else{
$searchResult = Product::where("pCategory", "like", $request->input('category'))
->where('pName', 'like', $request->input('search'))->get();
}
//dd($searchResult);
return view('products',['products' => $searchResult]);
}
And the model reads as follows:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'Product';
protected $primaryKey = 'pID';
//
public function orderDetails(){
return $this->hasMany('App\OrderDetail','ProductID','pID');
}
}
I don't understand why it keeps doing this, especially since I am not asking it to look at the ID. What is going on here?
Table structure:
CREATE TABLE [dbo].[Product] (
[pID] INT IDENTITY (1, 1) NOT NULL,
[pName] VARCHAR (50) NOT NULL,
[pBrand] VARCHAR (20) NOT NULL,
[pCurrentType] VARCHAR (10) NOT NULL,
[pVoltage] FLOAT (53) NOT NULL,
[pPrice] FLOAT (53) NOT NULL,
[pStock] INT NOT NULL,
[ImagePath] NVARCHAR (500) NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ([pID] ASC)
);
Upvotes: 1
Views: 4676
Reputation: 25
See the int value is inserted into the database as String. I mean int variable is within single quote. You have to remove it.
Upvotes: 0
Reputation:
First you don't have pCategory column in your table.
Second don't apply like clause for search when you receive all in category parameter.
public function productSearch(Request $request){
$searchResult = new Product;
if($request->has('search') && !empty($request->get('search')) && $request->get('search') !== 'all') {
$searchResult = $searchResult->where("pName", "like", '%'.$request->get('search'));
}
$searchResult = $searchResult->get();
return view('products',['products' => $searchResult]);
}
Upvotes: 2