search

Home  >  Q&A  >  body text

Check if record exists in any column

In my Laravel application, I need to check if there is a specific record in 20 columns in a table. I have searched for this answer but only found a way to check if it exists in a specific column but I need to check all columns and I was wondering if there is a way to do this without a loop, For example:

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

P粉917406009P粉917406009234 days ago470

reply all(1)I'll reply

  • P粉530519234

    P粉5305192342024-04-02 09:14:30

    Assume $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();
    

    reply
    0
  • Cancelreply