Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Aswathi's avatar

How to solve Laravel union queries different number of columns

I have two tables contact_us and upload_new_car.

contact_us table contains columns -

id, name, email, phone, message, created_at, updated_at

upload_new_car contains coloumns -

id , name, phone_number, car_name, car_price, location , car_model_year , car_model, variant, driven, fuel , transmission , city, no_of_owners, upload_1, upload_2, upload_3, upload_4, upload_5, created_at, updated_at

How can I get the UNION of these tables in Laravel? Please help

0 likes
3 replies
Aswathi's avatar

Thank you @alanholmes

Solved it :) $first = DB::table('contact_us') ->select(['id','name','email','phone','message','created_at','updated_at', DB::raw("'' as car_name, '' as car_price, '' as location, '' as car_model_year, '' as car_model, '' as variant, '' as driven, '' as fuel, '' as transmission, '' as city, '' as no_of_owners, '' as upload_1, '' as upload_2,'' as upload_3, '' as upload_4, '' as upload_5")]);

$union = DB::table('upload_new_car') ->select(['id','name',DB::raw("phone_number as phone, '' as message, '' as email"), 'car_name','car_price','location','car_model_year','car_model','variant', 'driven','fuel','transmission','city','no_of_owners','upload_1','upload_2','upload_3', 'upload_4','upload_5','created_at','updated_at']) ->union($first);

$query = DB::table(DB::raw("({$union->toSql()}) as x")) ->select(['id', 'name', 'phone','email','car_name','car_price','location', 'car_model_year','car_model','variant','driven','fuel','transmission','city', 'no_of_owners','upload_1','upload_2','upload_3','upload_4','upload_5','created_at', 'updated_at']);

return $query;

petergartin's avatar

This solution works, but it feels wrong that you have to do it this way. The fact that in order to union rows from different tables requires the same number of columns. And that there isn't a better way to fill in null columns on the smaller tables.

Please or to participate in this conversation.