Reputation: 3
Newbie to PHP/Laravel here.
Expected behavior
I want to use a form action to get data from database by inserting the id, something like the couriers tracking id. Until now it is working, but i want to show the results only if that id exist on the database
Code
Controller
public function search(Request $request)
{
$request->validate([
'query' => 'required|min:10|max:10',
]);
$query = $request->input('id');
$orders = Order::where('id','LIKE',"%$query%")->get();
$name = $request->input('id', '$id');
return view('order-details', compact('orders'));
order.blade
<form action="{{ route('order-details') }}" method="GET" class="order-form">
<div class="row">
<div class="col-lg-12">
<input type="text" placeholder="Track Order ID" name="query" id="query" value="{{ request()->input('query') }}">
</div>
<div class="col-lg-12">
<button type="submit">Submit Now</button>
</div>
</div>
</form>
@if(count($errors) > 0)
<ul>
@foreach ($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
@endif
route
Route::get('order', 'OrderController@index')->name('order');
Route::get('order-detail', 'OrderController@search')->name('order-details');
Upvotes: 0
Views: 5409
Reputation: 1138
You are using a wrong query.
$orders = Order::where('id','LIKE',"%$query%")->get();
The like operator will get anything like that query and not only.
You just need to remove the like operator to get only orders that match the exact id.
$orders = Order::where('id',$query)->get();
You can also add the exists rule:
The field under validation must exist on a given database table.
$request->validate([
'query' => 'exists:orders,id',
]);
Upvotes: 0
Reputation: 18926
I think your problem is you are using a like condition, like is notoriusly flakey on numbers.
$query = $request->input('id') ?? -1;
Order::where('id', $query)->get();
Where on only id, will only returns rows where id exists.
Upvotes: 2