I'm building a multi-tenant site where each account has their own set of users... In my Users controller, I have an update
method that fetches the user with the following:
$user = User::whereUsername($username)
->leftJoin('accounts', 'accounts.id', '=', 'users.account_id')
->where('accounts.id', '=', DB::raw('users.account_id'))
->where('accounts.subdomain', '=', $subdomain)
->firstOrFail();
Problem is, when I do $user->id
, it's giving me the accounts.id
instead...
I was able to fix this by adding ->select('users.id as id')
but I'd like to know why it happen and if there is a better way to avoid it. I would think that since I'm selecting from users
that the columns in the users
table would take priority in any naming conflicts...
There is no way for Laravel to know which id should take priority. Normally, if you would try to select it in SQL, you would get an error saying id is ambigeous. You can just select it in SQL by using its table name. To avoid confusion in Laravel, you could use aliases in your select statement. You did that, which is good. Try moving database related tasks out of your controller.