Support the ongoing development of Laravel.io →
Database Eloquent

I have a simple one-to-many relationship, like order to line items. I'm building a search form where the user can select the field they're searching on and the value they're searching for.

Order::with('items')->where(Input::get('field'), Input::get('val'))->get();

This works beautifully when the the field is part of the Order, I'm trying to figure out the Eloquent way to search items as well. So that if a user was to search the item->name field for "widget", it would return all orders that included a line item for a "widget".

Sorry, kind of a broad question, but that's what's making it difficult to find in the docs.

Last updated 3 years ago.
0

This is the solution I've come up with so far, but I don't really like it

$field = Input::get('field');
if ($field === 'item' || $field === 'sku'){
  $items = LineItem::where($field, 'LIKE', '%'.Input::get('val').'%')->get();
  $ids = [];
  foreach ($items as $item) {
    $ids[] = $item->order_id;
  }
  $orders = Order::with('item')->whereIn('id', $ids)->get();
} else {
  $orders = Order::with('item')->where($field, Input::get('val'))->get();
}
return View::make('searchPost', ['voters' => $voters]);
0

Sign in to participate in this thread!

Eventy

Your banner here too?

AdamColton adamcolton Joined 12 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.