Mukund Bharti
Mukund Bharti

Reputation: 261

How to merge two table data in laravel?

I need all users data in one blade, I have table1 and table2.

table1

'id','name','phone','email','status','created_at'

table2

'id','name','mobile','email','status','created_at'

I tried to do this but not an expected result.

 $usersTbl = DB::table('table1')->select('id','name','phone','email','status','created_at')->groupBy('phone')->paginate(20);

 $ordersTbl = DB::table('table2')->select('id','name','mobile','email','status','created_at')->groupBy('mobile')->paginate(20);

 $items=$ordersTbl->merge($usersTbl);
 dd($items);exit;

Upvotes: 1

Views: 10166

Answers (2)

Shamsheer
Shamsheer

Reputation: 744

Try This Method:

public function Details($id) {
    /** Make an empty array **/
        $patients = array();
    /** Get Data from first model **/
        $user_details = User::where(['id' => $id])->first();
    /** Get Data from second model **/
        $profile_details = Profile::where(['id' => $id])->first();
        $patients[] = $user_details; 
        $patients[] = $profile_details; 
        }
        return view('custom-view', compact('patients'));
    }

Upvotes: -1

TsaiKoga
TsaiKoga

Reputation: 13394

You have pagination, if you merge it the pagination need to recalculate.

You need to use unionAll and then paginate:

$usersTbl = DB::table('table1')->select('id','name','phone','email','status','created_at')->groupBy('phone');

$ordersTbl = DB::table('table2')->select('id','name','mobile AS phone','email','status','created_at')->groupBy('phone');

$mergeTbl = $usersTbl->unionAll($ordersTbl);
DB::table(DB::raw("({$mergeTbl->toSql()}) AS mg"))->mergeBindings($mergeTbl)->paginate(20);

Upvotes: 4

Related Questions