0

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');
Hamid Ali
  • 875
  • 1
  • 8
  • 22
  • No need this one `$name = $request->input('id', '$id');` delete this – STA Jun 28 '20 at 19:10
  • `$orders = Order::where('id', $query)->get();` try this. If id no exist, then you will get nothing on your query – STA Jun 28 '20 at 19:12

2 Answers2

2

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.

mrhn
  • 17,961
  • 4
  • 27
  • 46
  • I'm in doubt if the problem is to simple or we don't understand the whole problem, else gladly comment :) – mrhn Jun 28 '20 at 19:20
0

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',
        ]);
jewishmoses
  • 1,069
  • 2
  • 11
  • 16
  • To add to this, where clause will still not give the exact results, e.g., it's case insensitive. Naturally, MySQL does this as explained here https://stackoverflow.com/a/38578098/9902326 To get around this in Laravel, I used the following code `whereRaw('column = BINARY ?", $value)` – Rhys Cabonita Aug 02 '22 at 02:16