Home>

User table

id name prefecture

Product table

id product_name price expiration user_id

We have created a function that allows you to search for a certain product from the list screen based on the following conditions: 1, the prefecture in which the user who sent the item lives, 2, the expiration date of the product, 3, the price of the product. If each request has a value in the if statement, the value that meets the conditions is acquired. However, when searching by prefecture, an error is returned when the record is null, but if it is null, I want to run it as it is, but it does not work well. Also, it is not displayed unless you return a value to view with retuen in the if statement every time, but I would like to know if there is a better way. Also, if two conditions or three conditions are searched at the same time, do I have to write another process to display the matching values? It's a rudimentary thing, but I would like some advice.

ProductController.php

public function index(Request $request) {
   // Log::debug(print_r($order, true));
// Get the retrieved value
    $pref = $request->input('prefecture');
    $price_from = $request->input('price_from');
    $price_until = $request->input('price_until');
    $expiration = $request->input('expiration');
    $prefs = config('prefectures');
    $users = User::where('prefecture', $pref)->first();
    // Single property takes first, not get.
//Search by prefecture
if (isset($pref)) ($users = User::where('prefecture', $pref)->first();
    $products = $users->products()->paginate(10);
    return view('products.index', [
        'products' =>$products,
        'prefs' =>$prefs,
        ]);
}

// Search by expiration date
    if (isset($expiration)&&$expiration ==='not broken'){
    // Get today's date
    $today = Carbon::today();
    // Get product dated after today's date
    $products = Product::whereDate('expiration_date','>', $today ).
    ->paginate(10);
    return view('products.index', [
        'products' =>$products,
        'prefs' =>$prefs,
        ]);
    }elseif(isset($expiration )&&$expiration ==='broken') {
    $today = Carbon::today();
    $products = Product::whereDate('expiration_date','<', $today ).
    ->paginate(10);
    return view('products.index', [
        'products' =>$products,
        'prefs' =>$prefs,
        //'order' =>$order
        ]);
    }else {
    $products = Product::latest()->paginate(10);
    }
    // Search by price
    if (isset($price_from)&&isset($price_until)) (
        $products = Product::whereBetween('price', [$price_from,$price_until])
        ->paginate(10);
        }else {
        $products= Product::latest()->paginate(10);
        }
    return view('products.index', [
        'products' =>$products,
        'prefs' =>$prefs,
        ]);
    }

index.blade.php

<section>                Detailed search                  <form method="GET" action=""class="c-form p-form__login">        <ul><li>           <input type="number" placeholder="price" name="price_from" value="{{ old('price_from') }}">         </li>          <li>               Circle~
           </li>         <li>           <input type="number" placeholder="" name="price_until" value="{{ old('price_until')}}">         </li>         <li>               Circle
           </li>        </ul>         <ul>          <li>           <li>             <select name="prefecture">              <option value="">Convenience store prefecture</option>                 @foreach($prefs as $pref ).
                  <option value="{{ $pref }}"
                    @if(old('prefecture') === $pref) selected @endif
                    >{{$pref}}</option>                 @endforeach
              </select>        </li>        </li>        <li>          <li>          <select name="expiration">            <option value="" >Expiration date</option>            <option value="not broken"
                @if(old('expiration')==='not broken') selected @endif
                >Not broken
            </option>            <option value="broken"
                @if(old('expiration')==='broken') selected @endif
                >Broken
            </option>          </select>        </li>        </li>      </ul>                 <input type="submit" value="Search">           </form>      </section>
  • Answer # 1

    When I search by prefecture, an error is returned when the record is null.

    There are some mysteries in the question code in the first place.

    $users = User::where('prefecture', $pref)->first();


    This statement seems to be called twice in the first if statement and before it, but I think the latter is probably not what I intended.
    Also,$usersAs you can see, I would like to get multiple sellers, but the users acquired here are single or null. As the comment says, "a single property takes first, not get", you probably don't want a single here. And if it is null, it is natural to break in the method chain after this.

    But well, what you probably want to do is "extract the user's products that match the conditions", so do not do this. So instead of that, we use relation queries.whereHasCan be used.

    For example

      $users = User::where('prefecture', $pref)->first();
        $products = $users->products()->paginate(10);


    To replace the relation query with

    Product::whereHas('user', function($query) use ($pref) {
        $query->where('prefecture', $pref);
    });


    Can be written as


    What if I want to specify all the conditions when multiple search conditions are specified, I would like to connect the queries. The changes above are the first step towards that. Detailed code is omitted, but only the image.

    $query = new Product();
    if (condition 1) {
      $query = $query->where(...);
    }
    if (condition 2) {
      $query = $query->where(...);
    }
    ...
    $products = $query->paginate(10);
    return view(...);