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

yansusanto's avatar

Eloquent Relationship Problem

User Model

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

Order Model

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

Controller

    public function adminPostLogin()
    {

        $orders = Order::with('user')->paginate(5);

        return view('dashboard', compact('orders'));

    }

Blade

@foreach ($orders as $order)

{{ $order->id }}

{{ $order->user->name }} // why is this not working?

@endforeach 

Everything works fine except when I need to call up the user details, I'll get an error.

Am I missing something here?

Any input is greatly appreciated!

Thanks ;)

0 likes
50 replies
richard's avatar

In PHP, you cannot write a variable as $user-name. (using an hyphen)

We use underscores.

$user_name. is the correct variable.

Make sure you have a column on users table called user_name.

jrdavidson's avatar

So your saying you have a property on the user object called user-name?

First thing is don't hyphenate properties. Only use camelCalse or snake_case.

Secondly where is user-name coming from? Eloquent database results or generated somewhere else?

yansusanto's avatar

My bad it should be {{ $order->user->name }} that's the name of the user where the order belongs to which I'm trying to query from tables "users"

I'm guessing I'm not getting the relationship right.

Jaytee's avatar

For now, try this:

$orders = Order::with('user')->get(); // remove paginate and see if this returns results.

geowrgetudor's avatar

What is the relation between user & orders? What field from the orders connects them to the user?

Should be something like this

public function orders()
    {
        return $this->hasMany(Order::class, 'user_id`);
    }

public function user()
    {
        return $this->belongsTo(User::class, 'id', 'user_id');
    }
yansusanto's avatar

@Jaytee yes, it returns result with or without pagination. It doesn't work when I try to call the name of the user that the order belongs to.

@geowrge I tried that too but no, it doesn't work either.

yansusanto's avatar
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('facebook_id')->unique();   
            $table->string('avatar')->default('default.jpg');        
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password')->nullable();
            $table->boolean('isAdmin');
            $table->rememberToken();
            $table->timestamps();
        });
        Schema::create('orders', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();         
            $table->string('carNo')->unique();
            $table->string('panel');
            $table->string('long');
            $table->string('latt');
            $table->string('status');
            $table->timestamps();
        });
richard's avatar

@yansusanto Have you confirmed in the database that you have a user with an id lets say 1 in the users table and the user has a record associated with it in the orders table?

yansusanto's avatar

@richard

Yes, it is confirmed.

There are id and user_id & the rest of the columns in orders table.

Error

Trying to get property of non-object..
geowrgetudor's avatar

This is strange. It should work. As @richard said, check again if you have records in both tables and check if they are connected (id and user_id).

richard's avatar

This error usualy occures when you have a user id on orders table that does not exists on Users table. I presume there is a user you deleted that had a record on orders table already. (This is where the foreign key constraints is important)

Do you have so many records in the orders table? You can counter check with users table for that.

yansusanto's avatar

So if I set the relationship right, using `{{ $order->user->name }}' is the correct way of binding them, is it not?

yansusanto's avatar

@richard

I have checked on the DB and yes, I only have 3 users so far and all orders come with user_id.

richard's avatar

This is getting weird now.

try this on your web.php

Route::get('test'm function(){

    $order = App\Order::find(1); // Assume you have order with id of 1 has user_id = 2 

    echo $order->user->name; // Should display user's name where id = 2

});
yansusanto's avatar

@richard you're a WIZARD

I presume there is a user you deleted that had a record on orders table already. 

And yes, I deleted one user in the record and that was the issue. So it works now that I deleted that order.

Say the user has an option to delete his account, how do we prevent this?

1 like
yansusanto's avatar

@geowrge on both tables on just orders table?

And by the way, if I may ask

public function orders()
    {
        return $this->hasMany(Order::class, 'user_id`);
    }

user_id is the key that binds the two relationships, is that correct?

yansusanto's avatar

I like this

$table->unsingedTinyInteger('status')->default(1);

1 - Active 2 - Disabled 3 - Banned 4 - Deleted etc

Thank you!

yansusanto's avatar

Thanks, @geowrge and I tried to add to my Order Model

use SoftDeletes;

protected $dates = ['deleted_at'];

and my Order schema

$table->softDeletes();

Is that correct?

yansusanto's avatar

@richard thank you sir.

Since we're on the subject of ORM, if I may ask again

Order Model

    public function invoice()
    {
        return $this->hasOne(Invoice::class, 'order_id');
    }

Invoice Model

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

Is the relationship correct? Am I using hasOne correctly as each order will only have one invoice?

richard's avatar

No, you can do this on Order Model

public function invoice()
{
    return $this->hasOne(Invoice::class); // The ORM assumes you have a order_id column in the invoices table.
}
    

Also on Invoice Model, you don't need to be explicit. The function will automatically look for order_id column in the invoices table. (Adds _id at the end of function name. Like user() will be user_id, etc)

public function order() 
{
    return $this->belongsTo(Order::class);
}

therefore

$invoice = Invoice::find(1);
echo $invoice->order // Gets the order object associated with the invoice

$order = Order::find(1);
echo $order->invoice // Gets the invoice object associated with the order
yansusanto's avatar

Oh by the way, say I need an invoice ID that starts with 10001, how should I approach this?

Use the schema table default->10001? (that's beginner's thinking :P)

And when the number gets bigger, what happens?

richard's avatar

I think you need to start a new thread because this is a different issue. :)

1 like
yansusanto's avatar

Hi @richard. It's me again.

public function invoice()
{
    return $this->hasOne(Invoice::class);
}
public function orders() 
{
    return $this->belongsTo(Order::class);
}

Using the above relationship as per your suggestion, I still couldn't wrap my head around it.

What did I miss here?

    public function sendInvoice(Request $request)
    {

        $invoice = new Invoice;

        $invoice->orders()->create($request->all());

        return view('admin.dashboard');

    }

I'm trying to save an invoice that belongs to an order and I do have order_id in my invoice table.

PS: Pardon me if I've been asking too many questions.

Next

Please or to participate in this conversation.