how to get 2 table data into single variable array in laravel?

Viewed 1591

i have 2 tables User and subadmin consider user have 3 columns and subadmin has 2 column i want to get 3+2 (5 column) data into a single veriable array

the technique i want to use is that in user table i have id which is same in subadmin table with sub_admin_id(column) how i can use eloquent model to first link id with sub_admin_id and then into a single query get 5 column in single veriable array

here i am using to get data

$subadmindata = User::find($id)->get(); // [column1 ,column2 ,column3 ]
$subadmindata1 = SubAdmin::find($id)->get(); // [column1 ,column2 ]

output should be

$data = // [column1 ,column2 ,column3 , column4 ,column5 ]

note i dont want to use array merge or combine method i want to use eloquent model for my learning

5 Answers

you could use concat like this

$subadmindata = User::find($id)->get();
$subadmindata1 = SubAdmin::find($id)->get(); // it will return array of collections

$data = $subadmindata->concat($subadmindata1);

Notice when you use get after find it stop it's jobs so there is no need to find here

get() method will give you a collection not array, so you can merge two collection as follows.

   $subadmindata = User::find($id)->get();
   $subadmindata1 = SubAdmin::find($id)->get();

    $data = $subadmindata->merge($subadmindata1);

You can't use find with get(Assuming that you need a one result not all of the users). Try this. But looks like you need build the relationships correctly first. Anyway, quick answer is below.

$userCols = User::select('column1','col2','col3')->find($id);
$subAdminCols = SubAdmin::select('col4','col5')->find($id);
$cols = array_merge($userCols->toArray(), $subAdminCols->toArray());

you can use php ... operator to to push data

example like this

$subadmindata = User::find($id)->get()->toArray(); // [column1 ,column2 ,column3 ]
$subadmindata1 = SubAdmin::find($id)->get()->toArray(); // [column1 ,column2 ]
array_push($subadmindata, ...$subadmindata1);

return $subadmindata

ref link https://wiki.php.net/rfc/spread_operator_for_array

try this in user model

public function subadmin(){
        return $this->hasOne(SubAdmin::class,'sub_admin_id');
    }

in controller

    $sub_admins = User::find($id);
dd($sub_admins->subadmin->sub_admin_id)

   
Related