When i am entering hard coded id in Laravel controller, i am able to get data but when i enter same value in text box data i am getting error.
working Laravel controller
which shows value against id 123:
public function getdata(Request $request)
{
$files = Files::where('file_code','=','123')->first();
return response()->json([
'files'=> $files,
], 200);
}
Not working Laravel controller:
public function getdata(Request $request)
{
$file_code=Files::find($request->id);
$files = Files::where($file_code,'=','file_code')->get();
return response()->json([
'files'=> $files,
], 200);
}
error in log:
Column not found: 1054 Unknown column '' in 'where clause' (SQL: select * from `files` where `` = file_code)
VIEW:
<input v-model="state.file_code" type="text" placeholder="Enter file code">
<textarea v-model="state.files.text_data" placeholder="text appear here "></textarea>
<button @click="getdata" class="bg-green-800 rounded p-2 mb-5 text-white " >RECEIVE</button>
Get function:
function getdata(){
axios.get('http://127.0.0.1:8000/api/get-data',{
id: state.file_code,
})
.then(response=>{
state.files=response.data.files;
});
}
Route:
Route::get('get-data',[FilesController::class,'getdata']);
CodePudding user response:
Your issue is here:
Route:
Route::get('get-data',[FilesController::class,'getdata']);
Controller:
$file_code=Files::find($request->id);
$files = Files::where($file_code,'=','file_code')->get();
Your route doesn't specify an {id}
variable, so $request->id
in your controller will always be null
.
Then you're trying to get a Files
object with Files::find(null)
, which will also always return null
, i.e. $file_code
is null
.
Then you're looking for another Files
object with Files::where(null,'=','file_code')->get();
. This line will return all Files
object where the null
or ""
column is "file_code"
.
What you probably want to do is something like:
Route:
Route::get('get-data/{id}',[FilesController::class,'getdata']);
Controller:
$files = Files::find($request->id);