user7424490
user7424490

Reputation:

Laravel 8: How to send email notification to all admin users

I have a One To Many relationship between User Model & Order Model:

User.php:

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

Order.php:

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

Now I need to access user instance from order:

$order = Order::where('id', $id)->update(['status' => 'verified', 'price' => $data['price']]);
$user = $order->user;
dd($user);

But in this way, I get this error:

Trying to get property 'user' of non-object

So how to solve this issue and access user instance properly?

Here is the Migration of orders table:

Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('material');
            $table->string('color');
            $table->string('dimensions');
            $table->string('description')->nullable();
            $table->tinyInteger('user_id')->unsigned()->nullable();
            $table->timestamps();
        });

Upvotes: 0

Views: 620

Answers (2)

EnriqueRBT
EnriqueRBT

Reputation: 94

Why don`t you add in the migration the relation as a foreignID?

 $table->foreignID('user_id')->constrained();

Upvotes: 0

John Lobo
John Lobo

Reputation: 15319

update method wont return order detail's because update return true or false. So change it to

$order = Order::find($id);
$order->status='verified';
$order->price=$data['price'];
$order->save();
$user = $order->user;

update method takes array as argument update(array $values) and return int

Upvotes: 1

Related Questions