EduardoK
EduardoK

Reputation: 122

Check if record exists in ANY column

In my Laravel application, I need to check if any of my 20 columns in a table has a specific record. I've searched for this answer, but only found a way to check if it exists in a specific column, but i need to check in all columns, and i was wondering if there's a way to do that without a loop, something like:

DB::table('cart')->where($fileId->id)->exists();

Upvotes: 1

Views: 82

Answers (1)

Donkarnash
Donkarnash

Reputation: 12845

Assuming $field->id is the search term. You can try

//use Illuminate\Support\Facades\Schema;

$columns = Schema::getColumnListing('cart');

$query = DB::table('cart');

$firstColumn = array_shift($columns);
$query->where($firstColumn, $field->id);

foreach($columns as $column) {
    $query->orWhere($column, $field->id);
}

$result = $query->exists();

Upvotes: 0

Related Questions