Search code examples
phplaraveleloquentone-to-manylaravel-8

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();
        });

Solution

  • 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