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

potentdevelopment's avatar

Relationship Returns Null But Query Shows No Errors

So I am running this eloquent query:

$userInfo = $this->user->where('username', $username)->with('admin')->first();

When I do a dd() on $userInfo, it shows that the relations show null. I did a

dd(DB::getQueryLog());

Added screenshots below. https://potentdevelopment.com/pictures/sql-dump.png https://potentdevelopment.com/pictures/result-dump.png

And it shows that the query and the values passed are correct. Any help or clue would be appreciated.

Thanks!

0 likes
5 replies
MarianoMoreyra's avatar

Hi @potentdevelopment

What is $this->user ? It's an already loaded user? a relationship? An empty object of type User?

Normally, in this case you should be doing:

$userInfo = User::with('admin')->where('username', $username)->first();
potentdevelopment's avatar
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\User;
use App\Models\Admin;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Socialite;


class LoginController extends Controller
{
	
	public function __construct() {
		parent::__construct();
		$this->user    = new User();
	}

The user is being instantiated in the constructor. This isn't my code. I inherited the code and trying to make some sense of it since many of the setup isn't exactly how I would have done it.

Thanks!

siangboon's avatar

i guess, $this->user seem like loaded object, hence the where may filter only on the loaded object.

kreierson's avatar

I think it's because you are calling ->with('admin') on the $this object.

I'm assuming you are in some model calling a user relationship. the 'admin' relationship is probably on the 'User'model, not the model you are currently in.

You need to call ->with('admin') on the user model, not your current model. You could try

	 $this->user->where('username', $username)->with('user.admin')->first()

or

	User::with('admin')->where('username', $username)->where('this_id', $this->id)->first();

hard to say without seeing what else you have in your model and how the relationships are set up.

potentdevelopment's avatar
Level 2

So it was actually me being stupid. In the end, there wasn't anything wrong with the code. I was looking at the wrong DB via MySQL Workbench. Grrrrrr

Thank you all for your help!

Please or to participate in this conversation.