Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

daveb2's avatar

How to access model fields in ->leftJoin query?

Having an issue using left joins in queries involving multiple tables with fields of the same name.

I'm using the Spatie laravel permission module (https://spatie.be/docs/laravel-permission/v5/introduction), and I am trying to sort my users by their roles.

I'm also paginating the results, but the last line can be removed and replaced with a ->get() to remove pagination.

My eloquent query looks like:

return view('livewire.admin.user.index', [
	'users' => User::filter(
		['search' => $this->search]

	// join roles to order by them
	// credit to https://stackoverflow.com/a/61194625/4360876 for original inspiration
	)->leftJoin('model_has_roles', function ($join) {
		$join->on('model_has_roles.model_id', '=', 'users.id')
			->where('model_has_roles.model_type', '=', 'App\Models\User');
	})
	->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')

	// order by id
	->when($this->o_id == 'a', function ($query) {
		$query->orderBy('users.id', 'asc');
	})->when($this->o_id == 'd', function ($query) {
		$query->orderBy('users.id', 'desc');
	}

	// order by name
	)->when($this->o_name == 'a', function ($query) {
		$query->orderBy('users.name', 'asc');
	})->when($this->o_name == 'd', function ($query) {
		$query->orderBy('users.name', 'desc');
	}

	// order by email
	)->when($this->o_email == 'a', function ($query) {
		$query->orderBy('users.email', 'asc');
	})->when($this->o_email == 'd', function ($query) {
		$query->orderBy('users.email', 'desc');
	}

	// order by status
	)->when($this->o_status == 'a', function ($query) {
		$query->orderBy('roles.name', 'asc');
	})->when($this->o_status == 'd', function ($query) {
		$query->orderBy('roles.name', 'desc');
	}

	// order by last updated
	)->orderBy('users.updated_at', 'desc')

	->paginate(10)->onEachSide(0)
]);

This results in the SQL:

SELECT * FROM `users`
LEFT JOIN `model_has_roles` ON `model_has_roles`.`model_id` = `users`.`id`
and `model_has_roles`.`model_type` = 'App\Models\User'
LEFT JOIN `roles` ON `roles`.`id` = `model_has_roles`.`role_id`
WHERE `users`.`deleted_at` IS NULL
ORDER BY `users`.`updated_at` DESC LIMIT 10 OFFSET 0

This works, but running the raw SQL returns all the User model fields plus of course all the fields from the model_has_roles and roles tables.

Whilst this is not a problem for ordering as I can do things like $query->orderBy('users.name', 'desc'); and specify the table name as well as the field name, in my results the doubled fields are blank, and I don't know how to access the missing attributes:

^ Illuminate\Pagination\LengthAwarePaginator {#1851 ▼
	#items: Illuminate\Database\Eloquent\Collection {#1774 ▼
	#items: array:3 [▼
	0 => App\Models\User {#1775 ▼
		#connection: "mysql"
		#table: "users"
		#primaryKey: "id"
		#keyType: "int"
		+incrementing: true
		#with: []
		#withCount: []
		+preventsLazyLoading: false
		#perPage: 15
		+exists: true
		+wasRecentlyCreated: false
        #escapeWhenCastingToString: false
        #attributes: array:18 [▼
          "id" => null // 		******************************
          "name" => null // 	******************************
          "email" => "[email protected]"
          "email_verified_at" => null
          "password" => "<snip>"
          "two_factor_secret" => null
          "two_factor_recovery_codes" => null
          "remember_token" => null
          "current_team_id" => null
          "profile_photo_path" => null
          "notes" => null
          "created_at" => null
          "updated_at" => null
          "deleted_at" => null
          "role_id" => null
          "model_type" => null
          "model_id" => null
          "guard_name" => null

eg. in the above I am missing id and name for the user model.

Does anybody know how to access these missing attributes in the eloquent query results?

0 likes
2 replies
daveb2's avatar

@SilenceBringer Awesome, thank you! That works. Still getting my head around this eloquent syntax, especially eloquent vs DB facade/query syntax.

Please or to participate in this conversation.