Home » Php » php – Laravel LeftJoin Multiple queries with similer name

php – Laravel LeftJoin Multiple queries with similer name

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to show role name(roles table) in admin list(admins table). I work with leftJoin query:

   $data = Admin::select('admins.*', 'roles.name')
        ->leftJoin('model_has_roles', 'model_has_roles.model_id', '=', 'admins.id')
        ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
        ->get();

In Action print_r($data) I see This output:

(
[id] => 1
[name] => administrator
[email] => [email protected]
[password] => $2y$10$7/HMHGIPIJ6FiNBLy.BynurEhcsrbWkbc4wFREN9qjAFGNqSdaFTS
[remember_token] => 
[created_at] => 2020-02-11 10:46:45
[updated_at] => 2020-02-11 10:46:45
[sex] => 
[dob] => 
[mobile] => 
[phone] => 
[address] => 
[street] => 
[city] => 
[district] => 
[state] => 
[country] => 
[photo] => 
[web] => 
[status] => New
[upload_folder] => 
[deleted_at] => 
)

This Work But I can’t See admin name in list! In Output roles name replace with admin name.([name] => administrator).

How do can i fix this problem and show all value from admins table + name of roles table?!

How to&Answers:

You can alias your roles.name as below

Change

$data = Admin::select('admins.*', 'roles.name')

to

$data = Admin::select('admins.*', 'roles.name as RoleName')