How To Select Different Column of data as one with Laravel and MySql?

Laravel uses query builder to perform database operations so you don’t need to rewrite the query for different database Platform.

Let us assume a table with three column called cert1, cer2 and cert3

First we need to select the column with a desired name and then Union all of them together with common name selected.

$union1 = Info::whereNotNull('cert1')
->select('cert1 AS Certificate ')
->Where('cert1', 'like', $request->input('term') . '%');

$union2 = Info::whereNotNull('cert2'
)->select('cert2 AS Certificate ')
->Where('cert2', 'like', $request->input('term') . '%');

$union = Info::whereNotNull('cert3')
->select('cert3 AS Certificate ')
->Where('cert3', 'like', $request->input('term') . '%')
->union($union2)
->union($union1)
->groupby('union')->get();

Here Certificate is the common selected.

To write the same query in sql:-

SELECT a.`cert1` as Certificate FROM info as a 
UNION 
SELECT b.`cert2` as Certificate FROM info as b 
UNION 
SELECT c.`cert3` as Certificate FROM info as c

2 thoughts on “How To Select Different Column of data as one with Laravel and MySql?

Leave a Reply

Your email address will not be published. Required fields are marked *